JS Time Function Application addition, subtraction, comparison, format conversion of sample code _javascript tips

Source: Internet
Author: User
Tags date1

Copy Code code as follows:

JavaScript Document
//---------------------------------------------------
Judging leap years
//---------------------------------------------------
Date.prototype.isLeapYear = function () {
Return (0==this.getyear ()%4&& (This.getyear ()%100!=0) | | (This.getyear ()%400==0));
}

//---------------------------------------------------
Date formatting
Format Yyyy/yyyy/yy/yy represents year
Mm/m Month
W/W Week
dd/dd/d/d Date
hh/hh/h/h time
mm/m minutes
SS/SS/S/S seconds
//---------------------------------------------------
An extension to date that converts date to a string of the specified format
Months (m), days (d), hours (h), minutes (m), seconds (s), quarter (q) can be used with 1-2 placeholders,
Year (y) you can use 1-4 placeholders, milliseconds (s) to use only 1 placeholders (1-3-digit digits)
Example:
(New Date ()). Format ("Yyyy-mm-dd hh:mm:ss. S ") ==> 2006-07-02 08:09:04.423
(New Date ()). Format ("yyyy-m-d h:m:s.s") ==> 2006-7-2 8:9:4.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 (),//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;
}

/**
* An extension to date that converts date to a string of the specified format
* Month (M), Day (d), 12 hours (h), 24 hours (h), minutes (m), seconds (s), Week (E), quarter (q) can be 1-2 placeholders
* Year (Y) can be 1-4 placeholders, milliseconds (S) can only use 1 placeholders (1-3-digit digits)
* Eg:
* (New Date ()). Pattern ("Yyyy-mm-dd hh:mm:ss. S ") ==> 2006-07-02 08:09:04.423
* (New Date ()). Pattern ("Yyyy-mm-dd E HH:mm:ss") ==> 2009-03-10 II 20:09:04
* (New Date ()). Pattern ("Yyyy-mm-dd EE hh:mm:ss") ==> 2009-03-10 Tuesday 08:09:04
* (New Date ()). Pattern ("Yyyy-mm-dd EEE hh:mm:ss") ==> 2009-03-10 Tuesday 08:09:04
* (New Date ()). Pattern ("yyyy-m-d h:m:s.s") ==> 2006-7-2 8:9:4.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 (),//min
"S+": This.getseconds (),//sec
"q+": Math.floor (This.getmonth () +3)/3),//Quarter
"S": this.getmilliseconds ()//MS
};
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]): (("+ o[k]"). substr (("" + o[k). length));
}
}
return FMT;
}

//+---------------------------------------------------
//| The number of days for two time difference date format is 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); Seconds
Case ' n ': return new Date (Dttmp.getfullyear (), (Dttmp.getmonth ()), Dttmp.getdate (), dttmp.gethours (), dttmp.getminutes () +number, Dttmp.getseconds ()); Part
Case ' H ': return new Date (Dttmp.getfullyear (), (Dttmp.getmonth ()), Dttmp.getdate (), dttmp.gethours () +number, Dttmp.getminutes (), dttmp.getseconds ()); When
Case ' d ': return new Date (Dttmp.getfullyear (), (Dttmp.getmonth ()), Dttmp.getdate () +number, dttmp.gethours (), Dttmp.getminutes (), dttmp.getseconds ()); Days
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 ()); Years
}
}

//+---------------------------------------------------
//| Compare Date Difference dtend format is a date type or a valid date format string
//+---------------------------------------------------
Date.prototype.DateDiff = function (Strinterval, dtend) {
var dtstart = this;
if (typeof dtend = = ' string ')//if the string is converted to a 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 that overloads the system's ToString method
//+---------------------------------------------------
Date.prototype.toString = function (Showweek)
{
var mydate= this;
var str = mydate.tolocaledatestring ();
if (Showweek)
{
var Week = [' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six '];
STR + + ' Week ' + week[mydate.getday ()];
}
return str;
}

//+---------------------------------------------------
//| Validation of date legality
//| Format is: YYYY-MM-DD or YYYY/MM/DD
//+---------------------------------------------------
function Isvaliddate (DATESTR)
{
var sdate=datestr.replace (/(^\s+|\s+$)/g, ""); Go to both sides of the space;
if (sdate== ') return true;
If the format satisfies the yyyy-(/) mm-(/) DD or yyyy-(/) m (/) DD or yyyy-(/) m (/) d or yyyy-(/) mm-(/) d, replace with '
database, the legal date can be: Yyyy-mm/dd (2003-3/21), and the database is automatically converted to YYYY-MM-DD format
var s = sdate.replace (/[\d]{4,4}[\-/]{1}[\d]{1,2}[\-/]{1}[\d]{1,2}/g, ");
if (s== ')//description format meets 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 (' Wrong date format! The format is: Yyyy-mm-dd or YYYY/MM/DD. Notice leap year. ');
return false;
}
}
Else
{
Alert (' Wrong date format! The format is: Yyyy-mm-dd or YYYY/MM/DD. Notice leap year. ');
return false;
}
return true;
}

//+---------------------------------------------------
//| Date Time Check
//| Format is: 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 dates into groups
//+---------------------------------------------------
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;
}

//+---------------------------------------------------
//| Get Date data information
//| Parameter interval representing data types
//| Y year M month D Day W week WW Week h when N minutes s sec
//+---------------------------------------------------
Date.prototype.DatePart = function (interval)
{
var mydate = this;
var partstr= ';
var Week = [' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six '];
Switch (interval)
{
Case ' y ':p artstr = Mydate.getfullyear ();
Case ' m ':p artstr = Mydate.getmonth () +1;break;
Case ' d ':p artstr = Mydate.getdate ();
Case ' W ':p artstr = Week[mydate.getday ()];break;
Case ' ww ':p artstr = Mydate.weeknumofyear ();
Case ' h ':p artstr = mydate.gethours ();
Case ' n ':p artstr = Mydate.getminutes ();
Case ' s ':p artstr = Mydate.getseconds ();
}
return partstr;
}

//+---------------------------------------------------
//| Gets the maximum number of days of the month where the current date is
//+---------------------------------------------------
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;
}

//+---------------------------------------------------
//| string is converted to date type
//| Format mm/dd/yyyy mm-dd-yyyy 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 validation Code
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<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>
<body>
<input type= "button" title= "format" onclick= "Newdatetime ()" value= "Click to view"/>
</body>

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.