Home  >  Article  >  Web Front-end  >  JS date addition and subtraction functions organized

JS date addition and subtraction functions organized

巴扎黑
巴扎黑Original
2016-11-25 11:07:501158browse

// Add days
function AddDays(date,value)
{
date.setDate(date.getDate()+value);
}
// Add months
function AddMonths(date,value)
{
date.setMonth (date.getMonth()+value);
}
// Add year
function AddYears(date,value)
{
date.setFullYear(date.getFullYear()+value);
}
// Is it today
function IsToday(date)
{
return IsDateEquals(date,new Date());
}
// Whether it is the current month
function IsThisMonth(date)
{
return IsMonthEquals(date,new Date());
}
// Are the years of two dates equal? ​​
function IsMonthEquals(date1,date2)
{
return date1.getMonth()==date2.getMonth()&&date1.getFullYear()==date2.getFullYear();
}
/ / Determine whether the dates are equal
function IsDateEquals(date1,date2)
{
return date1.getDate()==date2.getDate()&&IsMonthEquals(date1,date2);
}
// Return the number of days in the month corresponding to a certain date
function GetMonthDayCount(date)
{
switch(date.getMonth()+1)
{
case 1:case 3:case 5:case 7:case 8:case 10:case 12:
return 31;
case 4 :case 6:case 9:case 11:
return 30;
}
//feb:
date=new Date(date);
var lastd=28;
date.setDate(29);
while(date.getMonth ()==1)
{
lastd++;
AddDays(date,1);
}
return lastd;
}
// Return the two-digit year
function GetHarfYear(date)
{
var v=date. getYear();
if(v>9)return v.toString();
return "0"+v;
}
// Return the month (corrected to two digits)
function GetFullMonth(date)
{
var v=date.getMonth()+1;
if(v>9)return v.toString();
return "0"+v;
}
// Return the day (corrected to two digits)
function GetFullDate( date)
{
var v=date.getDate();
if(v>9)return v.toString();
return "0"+v;
}
// Replace string
function Replace(str, from,to)
{
return str.split(from).join(to);
}
//Representation of formatted date
function FormatDate(date,str)
{
str=Replace(str,"yyyy" ,date.getFullYear());
str=Replace(str,"MM",GetFullMonth(date));
str=Replace(str,"dd",GetFullDate(date));
str=Replace(str," yy",GetHarfYear(date));
str=Replace(str,"M",date.getMonth()+1);
str=Replace(str,"d",date.getDate());
return str ;
}
//Uniform date format
function ConvertDate(str)
{
str=(str+"").replace(/^s*/g,"").replace(/s*$/g,"" ); // Remove the white space before and after
var d;
if(/^[0-9]{8}$/.test(str)) // 20040226 -> 2004-02-26
{
d=new Date(new Number(str.substr(0,4)),new Number(str.substr(4,2))-1,new Number(str.substr(6,2)));
if(d.getTime ())return d;
}
d=new Date(str);
if(d.getTime())return d;
d=new Date(Replace(str,"-","/"));
if(d.getTime())return d;
return null;
}
js time difference function