Javascript Date object Date Extension Method

Source: Internet
Author: User

Today, I have excerpted some methods related to date operations in js on the Internet. I 'd like to share with you. Copy codeThe Code is as follows: <script type = "text/javascript">
Date. prototype. Format = function (fmt)
{
// Author: meizz
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 (fmt ))
Fmt = fmt. replace (RegExp. $1, (this. getFullYear () + ""). substr (4-RegExp. $1. length ));
For (var k in o)
If (new RegExp ("(" + k + ")"). test (fmt ))
Fmt = fmt. replace (RegExp. $1, (RegExp. $1. length = 1 )? (O [k]): ("00" + o [k]). substr ("" + o [k]). length )));
Return fmt;
}
Date. prototype. addDays = function (d)
{
This. setDate (this. getDate () + d );
};
Date. prototype. addWeeks = function (w)
{
This. addDays (w * 7 );
};
Date. prototype. addMonths = function (m)
{
Var d = this. getDate ();
This. setMonth (this. getMonth () + m );
If (this. getDate () <d)
This. setDate (0 );
};
Date. prototype. addYears = function (y)
{
Var m = this. getMonth ();
This. setFullYear (this. getFullYear () + y );
If (m <this. getMonth ())
{
This. setDate (0 );
}
};
// Test var now = new Date (); now. addDays (1); // add or subtract a Date operation alert (now. Format ("yyyy-MM-dd "));
Date. prototype. dateDiff = function (interval, endTime)
{
Switch (interval)
{
Case "s": // calculate the second difference
Return parseInt (endTime-this)/1000 );
Case "n": // calculate the Score Difference
Return parseInt (endTime-this)/60000 );
Case "h": // calculate the time difference
Return parseInt (endTime-this)/3600000 );
Case "d": // calculate the daily difference
Return parseInt (endTime-this)/86400000 );
Case "w": // calculate the variance
Return parseInt (endTime-this)/(86400000*7 ));
Case "m": // calculate the monthly difference
Return (endTime. getMonth () + 1) + (endTime. getFullYear ()-this. getFullYear () * 12)-(this. getMonth () + 1 );
Case "y": // calculate the year difference
Return endTime. getFullYear ()-this. getFullYear ();
Default: // token has a token
Return undefined;
}
}
// Test var starTime = new Date ("2007/05/12 07:30:00"); var endTime = new Date ("2008/06/12 08:32:02"); document. writeln ("second difference:" + starTime. dateDiff ("s", endTime) + "<br>"); document. writeln ("difference:" + starTime. dateDiff ("n", endTime) + "<br>"); document. writeln ("Time Difference:" + starTime. dateDiff ("h", endTime) + "<br>"); document. writeln ("day difference:" + starTime. dateDiff ("d", endTime) + "<br>"); document. writeln ("latency difference:" + starTime. dateDiff ("w", endTime) + "<br>"); document. writeln ("month difference:" + starTime. dateDiff ("m", endTime) + "<br>"); document. writeln ("year difference:" + starTime. dateDiff ("y", endTime) + "<br> ");
</Script>

The specific extension method is as follows:
ParseCHS -- static method. Parse common Chinese dates and return date objects.
Add -- date addition and subtraction. [Note: This function also has a BUG when being uploaded. Please download and change the first line in this function to "var regExp =/^ \ d + $/;" to "var regExp =/^ ([+-])? \ D + $/; ", otherwise the subtraction cannot be done.]
DateDiff -- date difference. Returns the absolute value of the difference between the start date and the current date.
GetFirstWeekDays -- get the number of days in the first week of the year of the current date.
GetLastWeekDays -- get the number of days of the last week in the year of the current date.
GetWeeksOfYear -- Obtain the week number Of The Year of the current date.
GetWeek -- Obtain the week number of the year for the current date. Returns an integer.
GetSeason -- obtains the quarter of the year where the current date is located. Returns a quarter integer.
For detailed comments and parameters, see the comments in the JS file.Copy codeThe Code is as follows :/*
========================================================== ========================================================== =====
Description: Date object extension. Including common Chinese Date Format Parsing, addition and subtraction operations, date difference, weekly operations, and seasonal operations.
Author: Dezwen.
Date: 2009-5-30.
========================================================== ========================================================== =====
*/
Date. parseCHS = function (dateString ){
/// <Summary>
/// Parse common Chinese dates and return date objects.
/// </Summary>
/// <Param name = "dateString" type = "string">
/// Date string. The formats include: "xxxx (xx)-xx: xx", "xxxx (xx). xx. xx: xx ",
/// "Xxxx (xx)-xx: xx seconds"
/// </Param>
Var regExp1 =/^ \ d {4}-\ d {1, 2}-\ d {1, 2} (\ d {1, 2 }:\ d {1, 2 }: \ d {1, 2 })? $ /;
Var regExp2 =/^ \ d {4 }\. \ d {1, 2 }\. \ d {1, 2} (\ d {1, 2}: \ d {1, 2}: \ d {1, 2 })? $ /;
Var regExp3 =/^ \ d {4} year \ d {1, 2} month \ d {1, 2} Day (\ d {1, 2} hour \ d {1, 2} minute \ d {1, 2} seconds )? $ /;
If (regExp1.test (dateString )){}
Else if (regExp2.test (dateString )){
DateString = dateString. replace (/\./g ,"-");
}
Else if (regExp3.test (dateString )){
DateString = dateString. replace ("year", "-"). replace (
"Month", "-"). replace ("day", ""). replace ("Hour", ":"). replace ("Minute ",":"
). Replace ("seconds ","");
}
Else {
The format of the parameter value passed to Date. parseCHS by throw is incorrect. Please pass a valid date format string as the parameter. ";
}
Var date_time = dateString. split ("");
Var date_part = date_time [0]. split ("-");
Var time_part = (date_time.length> 1? Date_time [1]. split (":"):"");
If (time_part = ""){
Return new Date (date_part [0], date_part [1]-1, date_part [2]);
}
Else {
Return new Date (date_part [0], date_part [1]-1, date_part [2], time_part [0], time_part [1], time_part [2]);
}
}
Date. prototype. add = function (datepart, number, returnNewObjec ){
/// <Summary>
/// Add or subtract a date.
/// If the returnNewObjec parameter is set to true, the operation result is returned by a new date object, and the original date object remains unchanged,
/// Otherwise, the original date object is returned, and the value of the original date object is the operation result.
/// </Summary>
/// <Param name = "datepart" type = "string">
/// Date addition and subtraction:
/// Year, yy, yyyy -- Year
/// Quarter, qq, q-quarter
/// Month, mm, m -- Month
/// Dayofyear, dy, y -- day
/// Day, dd, d -- Day
/// Week, wk, ww -- Week
/// Hour, hh -- Hour
/// Minute, mi, n -- minute
/// Second, ss, s -- seconds
/// Millisecond, MS-millisecond
/// </Param>
/// <Param name = "number" type = "int">
/// Quantity to be added or subtracted
/// </Param>
/// <Param name = "returnNewObjec" type = "bool">
/// Whether to return a new date object. If the parameter is true, a new date object is returned; otherwise, the current date object is returned.
/// </Param>
/// <Returns type = "Date">
/// Return a date object
/// </Returns>
Var regExp =/^ \ d + $ /;
If (regExp. test (number )){
Number = parseInt (number );
}
Else {number = 0 ;}
Datepart = datepart. toLowerCase ();
Var tDate;
If (typeof (returnNewObjec) = "boolean "){
If (returnNewObjec = true ){
TDate = new Date (this );
}
Else {tDate = this ;}
}
Else {tDate = this ;}

Switch (datepart ){
Case "year ":
Case "yy ":
Case "yyyy ":
TDate. setFullYear (this. getFullYear () + number );
Break;
Case "quarter ":
Case "qq ":
Case "q ":
TDate. setMonth (this. getMonth () + (number * 3 ));
Break;
Case "month ":
Case "mm ":
Case "m ":
TDate. setMonth (this. getMonth () + number );
Break;
Case "dayofyear ":
Case "dy ":
Case "y ":
Case "day ":
Case "dd ":
Case "d ":
TDate. setDate (this. getDate () + number );
Break;
Case "week ":
Case "wk ":
Case "ww ":
TDate. setDate (this. getDate () + (number * 7 ));
Break;
Case "hour ":
Case "hh ":
TDate. setHours (this. getHours () + number );
Break
Case "minute ":
Case "mi ":
Case "n ":
TDate. setMinutes (this. getMinutes () + number );
Break
Case "second ":
Case "ss ":
Case "s ":
TDate. setSeconds (this. getSeconds () + number );
Break;
Case "millisecond ":
Case "ms ":
TDate. setMilliseconds (this. getMilliseconds () + number );
Break;
}
Return tDate;
}
Date. prototype. dateDiff = function (datepart, beginDate ){
/// <Summary>
/// Returns the absolute value of the difference between the start date and the current date.
/// </Summary>
/// <Param name = "datepart" type = "string">
/// Date addition and subtraction:
/// Year, yy, yyyy -- Year;
/// Quarter, qq, q-quarter
/// Month, mm, m -- Month
/// Dayofyear, dy, y -- day
/// Day, dd, d -- Day
/// Week, wk, ww -- Week
/// Hour, hh -- Hour
/// Minute, mi, n -- minute
/// Second, ss, s -- seconds
/// Millisecond, MS-millisecond
/// </Param>
/// <Param name = "beginDate" type = "DateTime">
/// Use it to compare my dates
/// </Param>
/// <Returns type = "int">
/// Return the absolute value of the date difference.
/// </Returns>
Datepart = datepart. toLowerCase ();
Var yearDiff = Math. abs (this. getFullYear ()-beginDate. getFullYear ());
Switch (datepart ){
Case "year ":
Case "yy ":
Case "yyyy ":
Return yearDiff;
Case "quarter ":
Case "qq ":
Case "q ":
Var qDiff = 0;
Switch (yearDiff ){
Case 0:
QDiff = Math. abs (this. getSeason ()-beginDate. getSeason ());
Break;
Case 1:
QDiff = (this. getSeason ()-new Date (this. getFullYear (), 0, 1). getSeason () +
(New Date (beginDate. getFullYear (), 11, 31). getSeason ()-
BeginDate. getSeason () + 1;
Break;
Default:
QDiff = (this. getSeason ()-new Date (this. getFullYear (), 0, 1). getSeason () +
(New Date (beginDate. getFullYear (), 11, 31). getSeason ()-
BeginDate. getSeason () + 1 + (yearDiff-1) * 4;
Break;
}
Return qDiff;
Case "month ":
Case "mm ":
Case "m ":
Var monthDiff = 0;
Switch (yearDiff ){
Case 0:
MonthDiff = Math. abs (this. getMonth ()-beginDate. getMonth ());
Break;
Case 1:
MonthDiff = (this. getMonth ()-new Date (this. getFullYear (), 0, 1). getMonth () +
(New Date (beginDate. getFullYear (), 11, 31). getMonth ()-
BeginDate. getMonth () + 1;
Break;
Default:
MonthDiff = (this. getMonth ()-new Date (this. getFullYear (), 0, 1). getMonth () +
(New Date (beginDate. getFullYear (), 11, 31). getMonth ()-
BeginDate. getMonth () + 1 + (yearDiff-1) * 12;
Break;
}
Return monthDiff;
Case "dayofyear ":
Case "dy ":
Case "y ":
Case "day ":
Case "dd ":
Case "d ":
Return Math. abs (this. setHours (0, 0, 0, 0)-beginDate. setHours (0, 0, 0, 0)/1000/60/60/24 );
Case "week ":
Case "wk ":
Case "ww ":
Var weekDiff = 0;
Switch (yearDiff ){
Case 0:
WeekDiff = Math. abs (this. getWeek ()-beginDate. getWeek ());
Break;
Case 1:
WeekDiff = (this. getWeek ()-new Date (this. getFullYear (), 0, 1). getWeek () +
(New Date (beginDate. getFullYear (), 11, 31). getWeek ()-
BeginDate. getWeek () + 1;
Break;
Default:

WeekDiff = (this. getWeek ()-new Date (this. getFullYear (), 0, 1). getWeek () +
(New Date (beginDate. getFullYear (), 11, 31). getWeek ()-
BeginDate. getWeek () + 1;
Var thisYear = this. getFullYear ();
For (var I = 1; I <yearDiff; I ++ ){
WeekDiff + = new Date (thisYear-I, 0, 1). getWeeksOfYear ();
}
Break;
}
Return weekDiff;
Case "hour ":
Case "hh ":
Return Math. abs (this-beginDate)/1000/60/60 );
Case "minute ":
Case "mi ":
Case "n ":
Return Math. abs (this-beginDate)/1000/60 );
Case "second ":
Case "ss ":
Case "s ":
Return Math. abs (this-beginDate)/1000 );
Case "millisecond ":
Case "ms ":
Return Math. abs (this-beginDate );
}
}
Date. prototype. getFirstWeekDays = function (){
/// <Summary>
/// Obtain the number of days in the first week of the year of the current date
/// </Summary>
Return (7-new Date (this. getFullYear (), 0, 1 ). getDay (); // the month in JS also starts from 0, and 0 indicates January, and so on.
}
Date. prototype. getLastWeekDays = function (year ){
/// <Summary>
/// Obtain the number of days of the last week in the year of the current date
/// </Summary>
Return (new Date (this. getFullYear (), 11, 31 ). getDay () + 1); // the month in JS also starts from 0. 0 indicates January, and so on.
}
Date. prototype. getWeeksOfYear = function (){
/// <Summary>
/// Obtain the week number Of The Year of the current date
/// </Summary>
Return (Math. ceil (new Date (this. getFullYear (), 11, 31, 23, 59, 59 )-
New Date (this. getFullYear (), 0, 1)/1000/60/60/24 )-
This. getFirstWeekDays ()-this. getLastWeekDays ()/7 + 2;
}
Date. prototype. getSeason = function (){
/// <Summary>
/// Obtain the quarter of the year where the current date is located. Returns a quarter integer.
/// </Summary>
Var month = this. getMonth ();
Switch (month ){
Case 0:
Case 1:
Case 2:
Return 1;
Case 3:
Case 4:
Case 5:
Return 2;
Case 6:
Case 7:
Case 8:
Return 3;
Default:
Return 4;
}
}
Date. prototype. getWeek = function (){
/// <Summary>
/// Obtain the week number of the year for the current date. Returns an integer.
/// </Summary>
Var firstDate = new Date (this. getFullYear (), 0, 1 );
Var firstWeekDays = this. getFirstWeekDays ();
Var secondWeekFirstDate = firstDate. add ("dd", firstWeekDays, true );
Var lastDate = new Date (this. getFullYear (), 11, 31 );
Var lastWeekDays = this. getLastWeekDays ();
If (this. dateDiff ("day", firstDate) <firstWeekDays ){
Return 1;
}
Else if (this. dateDiff ("day", lastDate) <lastWeekDays ){
Return this. getWeeksOfYear ();
}
Else {
Return Math. ceil (this-secondWeekFirstDate)/1000/60/60/24/7) + 1;
}
}

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.