Example of Date object extension in JavaScript

Source: Internet
Author: User
Tags current time getdate string format

I. Preface

The JavaScript Date object provides many Date-related attributes and Date-related methods, making it easier for websites to develop. However, the date format displayed on most web pages may be yyyy-MM-dd hh: mm: ss (similar to c # java ToString ()).

Whether it is the toString () method of the JavaScript Date object, the toGMTString (), toISOString (), and toLocaleDateString () methods of the JavaScript Date object, it cannot be converted into the Date string format that we usually want during development. At the same time, the JavaScript Date object is also provided for the encapsulation of addition, subtraction, and computation and request for Date. Then, the problem arises, what should we do when we need to perform date-related operations during the coding process? The best way is to encapsulate the commonly used date processing functions by yourself. The following code is some simple and practical date processing functions encapsulated during development. In the future development process, I will constantly improve, expand, and optimize these date processing functions.

II. Code

// Name: date addition function
// Parameter: part (year, month, day, hour, minute, second, millisecond)
// Return: Date object
Date. prototype. add = function (part, value ){
If (! Value | isNaN (value) value = 0;
Switch (part ){
Case "year ":
This. setFullYear (this. getFullYear () + value );
Break;
Case "month ":
This. setMonth (this. getMonth () + value );
Break;
Case "day ":
This. setDate (this. getDate () + value );
Break;
Case "hour ":
This. setHours (this. getHours () + value );
Break;
Case "minute ":
This. setMinutes (this. getMinutes () + value );
Break;
Case "second ":
This. setSeconds (this. getSeconds () + value );
Break;
Case "millisecond ":
This. setMilliseconds (this. getMilliseconds () + value );
Break;
Default:
     }
Return this;
};
 
Date. prototype. addYears = function (value ){
If (! Value | isNaN (value) value = 0;
This. setFullYear (this. getFullYear () + value );
Return this;
};
 
Date. prototype. addMonths = function (value ){
If (! Value | isNaN (value) value = 0;
This. setMonth (this. getMonth () + value );
Return this;
};
 
Date. prototype. addDays = function (value ){
If (! Value | isNaN (value) value = 0;
This. setDate (this. getDate () + value );
Return this;
};
 
Date. prototype. addHours = function (value ){
If (! Value | isNaN (value) value = 0;
This. setHours (this. getHours () + value );
Return this;
};
 
Date. prototype. addMinutes = function (value ){
If (! Value | isNaN (value) value = 0;
This. setMinutes (this. getMinutes () + value );
Return this;
};
 
Date. prototype. addSeconds = function (value ){
If (! Value | isNaN (value) value = 0;
This. setSeconds (this. getSeconds () + value );
Return this;
};
 
Date. prototype. addMilliseconds = function (value ){
If (! Value | isNaN (value) value = 0;
This. setMilliseconds (this. getMilliseconds () + value );
Return this;
};
 
// Name: date addition function
// Parameter: time (date string, for example: 12: 00: 00)
// Return: Date object
Date. prototype. addTime = function (time ){
Var timeRegex =/^ ([0-1]? \ D | 2 [0-3]) (: [0-5]? \ D) {1, 2} $/g;
If (timeRegex. test (time )){
Var value = Date. parse ("1970/1/1" + time)-Date. parse ("1970/1/1 ");
This. setMilliseconds (this. getMilliseconds () + value );
     }
Return this;
};
 
// Name: Date formatting function
// Parameter: format (example: yyyy-MM-dd hh: mm: ss), zeroize (whether to fill in zero)
// Return: date string
Date. prototype. toCustomString = function (format, zeroize ){
If (! Zeroize) zeroize = false;
Var dy = this. getFullYear ();
Var dM = this. getMonth () + 1;
Var dd = this. getDate ();
Var dh = this. getHours ();
Var dm = this. getMinutes ();
Var ds = this. getSeconds ();
Var dS = this. getMilliseconds ();
Var orm = {
"Y +": dy. toString (),
"M + ":! Zeroize? DM. toString (): dM <10? '0' + dM: dM. toString (),
"D + ":! Zeroize? Dd. toString (): dd <10? '0' + dd: dd. toString (),
"H + ":! Zeroize? Dh. toString (): dh <10? '0' + dh: dh. toString (),
"M + ":! Zeroize? Dm. toString (): dm <10? '0' + dm: dm. toString (),
"S + ":! Zeroize? Ds. toString (): ds <10? '0' + ds: ds. toString (),
"S": dS. toString ()
};
For (var I in orm ){
Var patt = new RegExp (I );
If (patt. test (format )){
Var item = orm [I];
Var MS = format. Matching (patt );
Var result = MS [0];
If (I = "S "){
Format = format. replace (result, item );
} Else {
Format = format. replace (result, item. substr (item. length-result. length ));
             }
         }
     }
Return format;
};
View Code
III. Analysis
1. add function: the first parameter of this function provides the part (year, month, day, hour, minute, second, millisecond) for date calculation, and returns the date object;

2. add # function: Similar to functions such as addYear, addMonth, and addDays. This is the decomposition of the add function and provides a more convenient and convenient function for date processing;

3. addTime function: This function provides date object type and time string type operations. The time parameter is a time string (example: 10: 00: 00 );

4. toCustomString function: This function provides the date object type to be converted to a date string of the specified format, format is the date format string parameter (example: yyyy-MM-dd hh: mm: ss );

In the following example, example 1 and example 2 demonstrate the use of the add function and add # function, and example 3 demonstrate the use of the addTime function.

The toCustomString function is used in all three examples to format and output the results.


// Example 1: The d1 data type is integer, with a date in milliseconds
Var d1 = Date. now ();
Var ret1 = new Date (d1). add ("year", 2); // Or: var ret1 = new Date (d1). addYear (2 );
Console. log (ret1.toCustomString ("yyyy-MM-dd hh: mm: ss "));
// Print: 19:15:45
 
// Example 2: d2 data type is string type, date string
Var d2 = "12:00:00 ";
Var ret2 = new Date (Date. parse (d2 )). add ("day", 10); // Or: var ret2 = new Date (Date. parse (d2 )). addDays (10 );
Console. log (ret2.toCustomString ("yyyy/MM/dd hh mm min ss seconds", true ));
// Print: 2016/01/11 12: 00 minutes and 00 seconds
 
// Example 3: Date and time string operations
Var ret3 = new Date (Date. now (). addTime ("2:10:00 ");
Console. log (ret3.toCustomString ("yyyy-MM-dd hh: mm: ss", true ));
// Print: 21:25:45

Let's take a look at an example of the time formatting function of the Date object.


Date. prototype. format = function (format)
{
Var o = {
"M +": this. getMonth () + 1, // month
"D +": this. getDate (), // day
"H +": this. getHours (), // hour
"M +": this. getMinutes (), // minute
"S +": this. getSeconds (), // second
"Q +": Math. floor (this. getMonth () + 3)/3), // quarter
"S": this. getMilliseconds () // millisecond
};
If (/(y +)/. test (format ))
    {   
Format = format. replace (RegExp. $1, (this. getFullYear () + ""). substr (4-RegExp. $1. length ));
    }
For (var k in o)
    {
If (new RegExp ("(" + k + ")"). test (format ))
        {
Format = format. replace (RegExp. $1, RegExp. $1. length = 1? O [k] :( "00" + o [k]). substr ("" + o [k]). length ));
        }
    }
Return format;
};

The call method is as follows:

Var dt = new Date ();
Var nowDate = dt. format ("yyyy-MM-dd hh: mm: ss ");

You can get the current time: 14:02:11

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.