JavaScript mimics the code _ time date of the DATEADD () function in the VBS

Source: Internet
Author: User
Tags getdate time interval
The project needs to use the calendar,. NET calendar control is too heavy, had to write with JS, the core function of the calendar is DateAdd (), the writing process found in JS inside operation time than the imagination of tedious, not like VBScript can easily DateAdd, and then think of using setFullYear (), setdate () and other built-in functions, you can flatten a JS version of the DATEADD (), the code is as follows:

Copy Code code as follows:

function DateAdd (interval,number,date) {//date can be either a time object or a string, and if it is the latter, the form must be: Yyyy-mm-dd Hh:mm:ss where the delimiter is indeterminate. "December 29, 2006 16:01 23 seconds" is also legal.
Number = parseint (number);
if (typeof (Date) = "string") {
Date = Date.split (/\d/);
--DATE[1];
Eval ("var date = new Date (" +date.join (",") + ")");
}
if (typeof (date) = = "Object") {
var date = Date
}
Switch (interval) {
Case "Y": Date.setfullyear (Date.getfullyear () +number); Break
Case "M": Date.setmonth (Date.getmonth () +number); Break
Case "D": Date.setdate (Date.getdate () +number); Break
Case "W": Date.setdate (Date.getdate () +7*number); Break
Case "H": Date.sethours (Date.gethour () +number); Break
Case "n": Date.setminutes (Date.getminutes () +number); Break
Case "S": Date.setseconds (Date.getseconds () +number); Break
Case "L": Date.setmilliseconds (Date.getmilliseconds () +number); Break
}
return date;
}


This function has tried to mimic the DateAdd function in VBScript, three parameters, the first is the change time interval, can be year, month, day, week, time, minute, second, millisecond (extension), the third parameter can be a time object, or a string (in the form must be: 2006-12-29 14:32:57 or December 29, 2006 14:32 57 seconds), the return value of the function is the new time object.
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.