Sample Code of js time function application addition, subtraction, comparison, and format conversion

Source: Internet
Author: User

Copy codeThe Code is as follows:
// JavaScript Document
//---------------------------------------------------
// 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
//---------------------------------------------------
// Extend the Date to convert the Date to a String in the specified format
// One to two placeholders can be used for month (M), Day (d), hour (h), minute (m), second (s), and quarter (q,
// Year (y) can use 1-4 placeholders, Millisecond (S) can only use 1 placeholder (1-3 digits)
// Example:
// (New Date (). Format ("yyyy-MM-dd hh: mm: ss. S") => 08:09:04. 423
// (New Date (). Format ("yyyy-M-d h: m: s. S") ==> 2006-7-2. 18
Date. prototype. Format = function (fmt)
{// Author: meizz
Var o = {
"M +": this. getMonth () + 1, // month
"D +": this. getDate (), // day
"H +": this. getHours (), // hour
"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;
}

/**
* Extended Date: converts Date to a String in the specified format.
* Month (M), Day (d), 12 hours (h), 24 hours (H), minute (m), second (s), Week (E), quarter (q) can use 1-2 placeholders
* Year (y) can use 1-4 placeholders, Millisecond (S) can only use 1 placeholder (1-3 digits)
* Eg:
* (New Date (). pattern ("yyyy-MM-dd hh: mm: ss. S") => 08:09:04. 423
* (New Date (). pattern ("yyyy-MM-dd e hh: mm: ss") => 20:09:04
* (New Date (). pattern ("yyyy-MM-dd EE hh: mm: ss") => 08:09:04 Tuesday
* (New Date (). pattern ("yyyy-MM-dd EEE hh: mm: ss") => 08:09:04 Tuesday
* (New Date (). pattern ("yyyy-M-d h: m: s. S") => 2006-7-2. 18
*/
Date. prototype. pattern = function (fmt ){
Var o = {
"M +": this. getMonth () + 1, // month
"D +": this. getDate (), // day
"H +": this. getHours () % 12 = 0? 12: this. getHours () % 12, // hour
"H +": this. getHours (), // hour
"M +": this. getMinutes (), // minute
"S +": this. getSeconds (), // second
"Q +": Math. floor (this. getMonth () + 3)/3), // quarter
"S": this. getMilliseconds () // millisecond
};
Var week = {
"0": "/u65e5 ",
"1": "/u4e00 ",
"2": "/u4e8c ",
"3": "/u4e09 ",
"4": "/u56db ",
"5": "/u4e94 ",
"6": "/u516d"
};
If (/(y +)/. test (fmt )){
Fmt = fmt. replace (RegExp. $1, (this. getFullYear () + ""). substr (4-RegExp. $1. length ));
}
If (/(E +)/. test (fmt )){
Fmt = fmt. replace (RegExp. $1, (RegExp. $1. length> 1 )? (RegExp. $1. length> 2? "/U661f/u671f": "/u5468"): "") + week [this. getDay () + ""]);
}
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;
}

// + ---------------------------------------------------
// | 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 (dtTmp. getFullYear (), (dtTmp. getMonth (), dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds () + Number); // second
Case 'N': return new Date (dtTmp. getFullYear (), (dtTmp. getMonth (), dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes () + Number, dtTmp. getSeconds (); // minute
Case 'H': return new Date (dtTmp. getFullYear (), (dtTmp. getMonth (), dtTmp. getDate (), dtTmp. getHours () + Number, dtTmp. getMinutes (), dtTmp. getSeconds (); // hour
Case 'D': return new Date (dtTmp. getFullYear (), (dtTmp. getMonth (), dtTmp. getDate () + Number, dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds (); // day
Case 'W': return new Date (dtTmp. getFullYear (), (dtTmp. getMonth (), dtTmp. getDate () + Number * 7, dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds (); // week
Case 'q': return new Date (dtTmp. getFullYear (), (dtTmp. getMonth () + Number * 3, dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds (); // quarter
Case 'M': return new Date (dtTmp. getFullYear (), (dtTmp. getMonth () + Number, dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds (); // month
Case 'y': return new Date (dtTmp. getFullYear () + Number), dtTmp. getMonth (), dtTmp. getDate (), dtTmp. getHours (), dtTmp. getMinutes (), dtTmp. getSeconds (); // year
}
}

// + ---------------------------------------------------
// | 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;
}

// + ---------------------------------------------------
// | 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;
}

Page Verification Code
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>
<Script src = "timedata. js" type = "text/javascript"> </script>

<Script type = "text/javascript">
Var nowtime = new Date ();
Function newdatetime (){
Nowtime = nowtime. DateAdd ("h", 35 );
Str = nowtime. Format ("yyyy-MM-dd HH: mm: ss ");
Alert (str );

}
</Script>

<Title> untitled document </title>
</Head>
<Body>
<Input type = "button" title = "format" onclick = "newdatetime ()" value = "click to view"/>
</Body>
</Html>

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.