Javascript Date and Time Functions (Classic + perfect + practical) _ time and date

Source: Internet
Author: User
Date and Time script library method list Date. prototype. isLeapYear judge leap year
Date. prototype. Format
Date. prototype. DateAdd Date calculation
Date. prototype. DateDiff compare Date difference
Date. prototype. toString Date to string
Date. prototype. toArray Date is split into Arrays
Date. prototype. DatePart obtains part of the Date information.
Date. prototype. MaxDayOfDate indicates the maximum number of days in the month where the Date is located.
Date. prototype. WeekNumOfYear determine the week of the year where the Date is located
StringToDate string to date type
IsValidDate verification date validity
CheckDateTime full Date and Time check
DaysBetween date day difference

The Code is as follows:


//---------------------------------------------------
// Determine the leap year
//---------------------------------------------------
Date. prototype. isLeapYear = function ()
{
Return (0 = this. getYear () % 4 & (this. getYear () % 100! = 0) | (this. getYear () % 400 = 0 )));
}
//---------------------------------------------------
// Format the date
// Format: YYYY/yyyy/YY/yy indicates the year
// MM/M month
// W/w weeks
// Dd/DD/d/D Date
// Hh/HH/h/H time
// Mm/m minutes
// Ss/SS/s/S seconds
//---------------------------------------------------
Date. prototype. Format = function (formatStr)
{
Var str = formatStr;
Var Week = ['day', 'yi', '2', '3', '4', '5', '6'];
Str = str. replace (/yyyy | YYYY/, this. getFullYear ());
Str = str. replace (/yy | YY/, (this. getYear () % 100)> 9? (This. getYear () % 100). toString (): '0' + (this. getYear () % 100 ));
Str = str. replace (/MM/, this. getMonth ()> 9? This. getMonth (). toString (): '0' + this. getMonth ());
Str = str. replace (/M/g, this. getMonth ());
Str = str. replace (/w | W/g, Week [this. getDay ()]);
Str = str. replace (/dd | DD/, this. getDate ()> 9? This. getDate (). toString (): '0' + this. getDate ());
Str = str. replace (/d | D/g, this. getDate ());
Str = str. replace (/hh | HH/, this. getHours ()> 9? This. getHours (). toString (): '0' + this. getHours ());
Str = str. replace (/h | H/g, this. getHours ());
Str = str. replace (/mm/, this. getMinutes ()> 9? This. getMinutes (). toString (): '0' + this. getMinutes ());
Str = str. replace (/m/g, this. getMinutes ());
Str = str. replace (/ss | SS/, this. getSeconds ()> 9? This. getSeconds (). toString (): '0' + this. getSeconds ());
Str = str. replace (/s | S/g, this. getSeconds ());
Return str;
}
// + ---------------------------------------------------
// | Returns the number of days difference between two time ranges in the format of YYYY-MM-dd.
// + ---------------------------------------------------
Function daysBetween (DateOne, DateTwo)
{
Var OneMonth = DateOne. substring (5, DateOne. lastIndexOf ('-'));
Var OneDay = DateOne. substring (DateOne. length, DateOne. lastIndexOf ('-') + 1 );
Var OneYear = DateOne. substring (0, DateOne. indexOf ('-'));
Var TwoMonth = DateTwo. substring (5, DateTwo. lastIndexOf ('-'));
Var TwoDay = DateTwo. substring (DateTwo. length, DateTwo. lastIndexOf ('-') + 1 );
Var TwoYear = DateTwo. substring (0, DateTwo. indexOf ('-'));
Var cha = (Date. parse (OneMonth + '/' + OneDay + '/' + OneYear)-Date. parse (TwoMonth + '/' + TwoDay + '/' + TwoYear)/86400000 );
Return Math. abs (cha );
}
// + ---------------------------------------------------
// | Date calculation
// + ---------------------------------------------------
Date. prototype. DateAdd = function (strInterval, Number ){
Var dtTmp = this;
Switch (strInterval ){
Case's ': return new Date (Date. parse (dtTmp) + (1000 * Number ));
Case 'N': return new Date (Date. parse (dtTmp) + (60000 * Number ));
Case 'H': return new Date (Date. parse (dtTmp) + (3600000 * Number ));
Case 'D': return new Date (Date. parse (dtTmp) + (86400000 * Number ));
Case 'W': return new Date (Date. parse (dtTmp) + (86400000*7) * Number ));
Case 'q': return new Date (dtTmp. getFullYear (), (dtTmp. getMonth () + Number * 3, dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds ());
Case 'M': return new Date (dtTmp. getFullYear (), (dtTmp. getMonth () + Number, dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds ());
Case 'y': return new Date (dtTmp. getFullYear () + Number), dtTmp. getMonth (), dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds ());
}
}
// + ---------------------------------------------------
// | Compare date difference dtEnd format is date type or valid Date Format String
// + ---------------------------------------------------
Date. prototype. DateDiff = function (strInterval, dtEnd ){
Var dtStart = this;
If (typeof dtEnd = 'string') // if the string is converted to the date type
{
DtEnd = StringToDate (dtEnd );
}
Switch (strInterval ){
Case's ': return parseInt (dtEnd-dtStart)/1000 );
Case 'N': return parseInt (dtEnd-dtStart)/60000 );
Case 'H': return parseInt (dtEnd-dtStart)/3600000 );
Case 'D': return parseInt (dtEnd-dtStart)/86400000 );
Case 'W': return parseInt (dtEnd-dtStart)/(86400000*7 ));
Case 'M': return (dtEnd. getMonth () + 1) + (dtEnd. getFullYear ()-dtStart. getFullYear () * 12)-(dtStart. getMonth () + 1 );
Case 'y': return dtEnd. getFullYear ()-dtStart. getFullYear ();
}
}
// + ---------------------------------------------------
// | Date output string, which reloads the system's toString Method
// + ---------------------------------------------------
Date. prototype. toString = function (showWeek)
{
Var myDate = this;
Var str = myDate. toLocaleDateString ();
If (showWeek)
{
Var Week = ['day', 'yi', '2', '3', '4', '5', '6'];
Str + = 'Week' + Week [myDate. getDay ()];
}
Return str;
}
// + ---------------------------------------------------
// | Date validity Verification
// | Format: YYYY-MM-DD or YYYY/MM/DD
// + ---------------------------------------------------
Function IsValidDate (DateStr)
{
Var sDate = DateStr. replace (/(^ \ s + | \ s + $)/g, ''); // remove spaces on both sides;
If (sDate = '') return true;
// If the format is YYYY-(/) MM-(/) DD Or YYYY-(/) M -(/) D or YYYY-(/) MM-(/) D is replaced''
// In the database, the valid date can be: YYYY-MM/DD (2003-3/21), the database will automatically convert to the YYYY-MM-DD format
Var s = sDate. replace (/[\ d] {4, 4} [\-/] {1} [\ d] {1} [\-/] {1} [\ d] {1, 2} /g, '');
If (s = '') // The description format meets the YYYY-MM-DD or YYYY-M-DD or YYYY-M-D or YYYY-MM-D
{
Var t = new Date (sDate. replace (/\-/g ,'/'));
Var ar = sDate. split (/[-/:]/);
If (ar [0]! = T. getYear () | ar [1]! = T. getMonth () + 1 | ar [2]! = T. getDate ())
{
// Alert ('incorrect Date Format! Format: YYYY-MM-DD or YYYY/MM/DD. Pay attention to the leap year. ');
Return false;
}
}
Else
{
// Alert ('incorrect Date Format! Format: YYYY-MM-DD or YYYY/MM/DD. Pay attention to the leap year. ');
Return false;
}
Return true;
}
// + ---------------------------------------------------
// | Date and Time check
// | Format: YYYY-MM-DD HH: MM: SS
// + ---------------------------------------------------
Function CheckDateTime (str)
{
Var reg =/^ (\ d +)-(\ d {1, 2})-(\ d {1, 2}) (\ d {1, 2}) :( \ d {1, 2 }) :( \ d {1, 2}) $ /;
Var r = str. match (reg );
If (r = null) return false;
R [2] = r [2]-1;
Var d = new Date (r [1], r [2], r [3], r [4], r [5], r [6]);
If (d. getFullYear ()! = R [1]) return false;
If (d. getMonth ()! = R [2]) return false;
If (d. getDate ()! = R [3]) return false;
If (d. getHours ()! = R [4]) return false;
If (d. getMinutes ()! = R [5]) return false;
If (d. getSeconds ()! = R [6]) return false;
Return true;
}
// + ---------------------------------------------------
// | Split the date into an array
// + ---------------------------------------------------
Date. prototype. toArray = function ()
{
Var myDate = this;
Var myArray = Array ();
MyArray [0] = myDate. getFullYear ();
MyArray [1] = myDate. getMonth ();
MyArray [2] = myDate. getDate ();
MyArray [3] = myDate. getHours ();
MyArray [4] = myDate. getMinutes ();
MyArray [5] = myDate. getSeconds ();
Return myArray;
}
// + ---------------------------------------------------
// | Obtain date data
// | Interval indicates the data type.
// | Y, m, D, w, week ww, week h, n minutes, s
// + ---------------------------------------------------
Date. prototype. DatePart = function (interval)
{
Var myDate = this;
Var partStr = '';
Var Week = ['day', 'yi', '2', '3', '4', '5', '6'];
Switch (interval)
{
Case 'y': partStr = myDate. getFullYear (); break;
Case 'M': partStr = myDate. getMonth () + 1; break;
Case 'D': partStr = myDate. getDate (); break;
Case 'W': partStr = Week [myDate. getDay ()]; break;
Case 'ww ': partStr = myDate. WeekNumOfYear (); break;
Case 'H': partStr = myDate. getHours (); break;
Case 'N': partStr = myDate. getMinutes (); break;
Case's ': partStr = myDate. getSeconds (); break;
}
Return partStr;
}
// + ---------------------------------------------------
// | Obtain the maximum number of days in the month of the current date
// + ---------------------------------------------------
Date. prototype. MaxDayOfDate = function ()
{
Var myDate = this;
Var ary = myDate. toArray ();
Var date1 = (new Date (ary [0], ary [1] + 1, 1 ));
Var date2 = date1.dateAdd (1, 'M', 1 );
Var result = dateDiff (date1.Format ('yyyy-MM-dd'), date2.Format ('yyyy-MM-dd '));
Return result;
}
// + ---------------------------------------------------
// | The week in which the current date is obtained is the week of the year.
// + ---------------------------------------------------
Date. prototype. WeekNumOfYear = function ()
{
Var myDate = this;
Var ary = myDate. toArray ();
Var year = ary [0];
Var month = ary [1] + 1;
Var day = ary [2];
Document. write ('<script language = VBScript \> \ n ');
Document. write ('mydate = DateValue (''+ month + '-' + day + '-' + year +'') \ n ');
Document. write ('result = DatePart ('ww ', myDate) \ n ');
Document. write ('\ n ');
Return result;
}
// + ---------------------------------------------------
// | Convert string to date type
// | MM/dd/yyyy mm-dd-YYYY/MM/dd YYYY-MM-dd
// + ---------------------------------------------------
Function StringToDate (DateStr)
{
Var converted = Date. parse (DateStr );
Var myDate = new Date (converted );
If (isNaN (myDate ))
{
// Var delimCahar = DateStr. indexOf ('/')! =-1? '/':'-';
Var arys = DateStr. split ('-');
MyDate = new Date (arys [0], -- arys [1], arys [2]);
}
Return myDate;
}

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.