1. In JS, the eval () method converts the string format data into a date format
function GetDate (strdate) {//strdate is a string that needs to be converted to a date format var date = eval (' New date (' + Strdate.replace ') (/\d+ (? =-[^ -]+$)/, function (a) {return parseint (A, 10)-1;}). Match (/\d+/g) + ') '; return date; }
2. Get the date of the day before the current date
function Getyestoday (date) { var yesterday_milliseconds=date.gettime () -1000*60*60*24; var yesterday = new Date (); Yesterday.settime (yesterday_milliseconds); var stryear = Yesterday.getfullyear (); var strday = Yesterday.getdate (); var strmonth = Yesterday.getmonth () +1; if (strmonth<10) { strmonth= "0" +strmonth; } DATASTR = stryear+ "-" +strmonth+ "-" +strday; return datastr; }
3. Get the date last month on this day
function Getlastmonthyestday (date) { var daysinmonth = new Array ([0],[31],[28],[31],[30],[31],[30],[31],[31],[30 ],[31],[30],[31]); var stryear = Date.getfullyear (); var strday = Date.getdate (); var strmonth = Date.getmonth () +1; if (stryear%4 = = 0 && stryear%100! = 0) { daysinmonth[2] =; } if (strMonth-1 = = 0) { Stryear-= 1; Strmonth = n; } else { Strmonth-= 1; } Strday = Daysinmonth[strmonth] >= strday? Strday:daysinmonth[strmonth]; if (strmonth<10) { strmonth= "0" +strmonth; } if (strday<10) { strday= "0" +strday; } DATASTR = stryear+ "-" +strmonth+ "-" +strday; return datastr; }
4. Get the date of last year on this day
function Getlastyearyestdy (date) { var stryear = date.getfullyear ()-1; var strday = Date.getdate (); var strmonth = Date.getmonth () +1; if (strmonth<10) { strmonth= "0" +strmonth; } if (strday<10) { strday= "0" +strday; } DATASTR = stryear+ "-" +strmonth+ "-" +strday; return datastr; }
5, get the date of next month on this day
function GetLastMonthYestdy2 (date) { var daysinmonth = new Array ([0],[31],[28],[31],[30],[31],[30],[31],[31],[30 ],[31],[30],[31]); var stryear = Date.getfullyear (); var strday = Date.getdate (); var strmonth = Date.getmonth () +1; if (stryear%4 = = 0 && stryear%100! = 0) { daysinmonth[2] =; } if (strmonth + 1 = =) { stryear + = 1; Strmonth = 1; } else { Strmonth + = 1; } Strday = Daysinmonth[strmonth] >= strday? Strday:daysinmonth[strmonth]; if (strmonth<10) { strmonth= "0" +strmonth; } if (strday<10) { strday= "0" +strday; } DATASTR = stryear+ "-" +strmonth+ "-" +strday; return datastr; }
6. Testing
$ (function () { var strdate = ' 2014-06-11 '; $ ("#test"). HTML ("Use the eval () method to convert a string to a time format:" + getDate (strdate) + "<br/>" + "gets the date before the current date:" + getyestoday ( GetDate (strdate) + "<br/>" + "get the date last month on this day:" + getlastmonthyestday (getDate (strdate)) + "<br/>" + "Get the date of last year on this day:" + getlastyearyestdy (getDate (strdate)) + "<br/>" + "get the date of next month on this day:" + GetLastMonthYestdy2 (GetDate (strdate)) + "<br/>"); })
7. Test results