Javascript Date Object Date extension method _ Time Date

Source: Internet
Author: User
Tags abs getdate
Today, some of the online excerpts of the operation date of the relevant methods, and now share with you.
Copy Code code 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 (),//min
"S+": This.getseconds (),//sec
"q+": Math.floor (This.getmonth () + 3)/3),//Quarter
"S": this.getmilliseconds ()//MS
};
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]): (("+ 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 minus 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 Difference
Return parseint ((endtime-this)/60000);
Case "H"://Calculate time difference
Return parseint ((endtime-this)/3600000);
Case "D"://Calculate Day Difference
Return parseint ((endtime-this)/86400000);
Case "W"://Calculate Week Difference
Return parseint ((endtime-this)/(86400000*7));
Case "M"://Calculate month Difference
Return (Endtime.getmonth () +1) + ((Endtime.getfullyear ()-this.getfullyear ()) *12)-(This.getmonth () +1);
Case "Y"://Calculate Year Difference
Return Endtime.getfullyear ()-this.getfullyear ();
Default://Input Error
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 ("Week 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 following methods are specifically extended:
parsechs--static method. Resolves the commonly used Chinese dates and returns the date objects.
add--date plus minus operation. [Note: There is a bug in this function when uploading.] Please download the first line of this function "var regExp =/^\d+$/;" to "var regExp =/^ ([+-])? \d+$/;" Or else you can't subtract. ]
datediff--date difference. The difference between the start date and the current date, and returns the absolute value of the difference.
getfirstweekdays--gets the number of days of the first one weeks in the year in which the current date is located.
getlastweekdays--gets the number of days in the last one weeks of the year in which the current date is located.
getweeksofyear--gets the number of weeks for the year in which the current date is located.
getweek--get the current date is the week ordinal of the year. Returns an integer value.
getseason--get the current date is the first quarter of the year. Returns a quarter integer value.
For detailed comments and parameters, please refer to the comments in the JS file.
Copy Code code as follows:

/*
=====================================================================================
Description:date object extension. It includes common Chinese date format parsing, addition and subtraction operation, date difference, weekly operation and quarterly operation.
Author:dezwen.
Date:2009-5-30.
=====================================================================================
*/
Date.parsechs = function (datestring) {
<summary>
Resolves the commonly used Chinese dates and returns the date objects.
</summary>
<param name= "datestring" type= "string" >
A date string. Contains the format: "xxxx (XX)-xx-xx xx:xx:xx", "xxxx (XX). xx.xx xx:xx:xx",
"xxxx (xx) xx days xx xx xx x 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} \d{1,2} seconds)? \d{1,2;
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 ("When", ":"). Replace ("Min", ":")
). Replace ("Seconds", "");
}
else {
Throw "The parameter value passed to Date.parsechs is not in the correct format. Please pass a valid date format string as a 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>
Date plus minus.
If the Returnnewobjec argument is a true value, the result of the operation is returned by a new Date object, the original Date object is unchanged,
Otherwise, the original date object is returned, at which point the value of the original Date object is the result of the operation.
</summary>
<param name= "datepart" type= "string" >
Part of the date plus minus:
Year, YY, yyyy--years
Quarter, QQ, Q--season
Month, MM, M--month
DayOfYear, DY, y--day
Day, DD, D--days
Week, WK, ww--Zhou
Hour, HH--hour
Minute, MI, N--minutes
Second, SS, S--seconds
Millisecond, MS--MS
</param>
<param name= "number" type= "int" >
Quantity to be added and reduced
</param>
<param name= "RETURNNEWOBJEC" type= "bool" >
Whether to return a new Date object. If the argument is a true value, a new Date object is returned, otherwise the current date object is returned.
</param>
<returns type= "Date" >
Returns 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>
The difference between the start date and the current date, and returns the absolute value of the difference.
</summary>
<param name= "datepart" type= "string" >
Part of the date plus minus:
Year, YY, yyyy--years;
Quarter, QQ, Q--season
Month, MM, M--month
DayOfYear, DY, y--day
Day, DD, D--days
Week, WK, ww--Zhou
Hour, HH--hour
Minute, MI, N--minutes
Second, SS, S--seconds
Millisecond, MS--MS
</param>
<param name= "Begindate" type= "DateTime" >
To be used to compare my dates
</param>
<returns type= "int" >
Returns 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 (), one,). Getseason ()-
Begindate.getseason ()) + 1;
Break
Default
Qdiff = (This.getseason ()-New Date (This.getfullyear (), 0, 1). Getseason ()) +
(New Date (Begindate.getfullyear (), one,). 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 (), one,). GetMonth ()-
Begindate.getmonth ()) + 1;
Break
Default
Monthdiff = (This.getmonth ()-New Date (This.getfullyear (), 0, 1). GetMonth ()) +
(New Date (Begindate.getfullyear (), one,). 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 (), one,). Getweek ()-
Begindate.getweek ()) + 1;
Break
Default

Weekdiff = (This.getweek ()-New Date (This.getfullyear (), 0, 1). Getweek ()) +
(New Date (Begindate.getfullyear (), one,). 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>
Gets the number of days of the one week in the year in which the current date is located
</summary>
Return (7-new Date (this.getfullyear (), 0, 1). Getday ()); The month in JS is also starting from 0, and 0 means January, and so forth.
}
Date.prototype.getLastWeekDays = function (year) {
<summary>
Gets the number of days in the last one weeks of the year in which the current date is located
</summary>
Return (New Date (This.getfullyear (), one,). Getday () + 1); The month in JS is also starting from 0, and 0 means January, and so forth.
}
Date.prototype.getWeeksOfYear = function () {
<summary>
Gets the number of weeks in the year in which the current date is
</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>
Get the current date is the first quarter of the year. Returns a quarter integer value.
</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>
Gets the current date is the week ordinal of the year. Returns an integer value.
</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.