Preface: Recently in a date selection function, in the date of conversion often to Halo, summed up the use of commonly used date objects, to facilitate the future direct view using ~
1. The new Date () is used in the following ways:
-
- Do not receive any parameters: returns the current time;
- Receives a parameter x: Returns the value of January 1, 1970 + x milliseconds.
- New Date (1, 1, 1) returns February 1, 1901.
- The new Date (2016, 1, 1) does not add 2016 to the 1900 basis, but only represents February 1, 2016.
2. Use new date to convert time to date object
Note: The time format needs to be 1999/12/31 23:59 (not 1999-12-30 23:43), otherwise there may be an error on some models.
3. Some common APIs for date objects
Newdate () data after conversion, you can use the following API directlyNewDate (x). GetMonth () +1//Get MonthNewDate (x). getDate//Get DateNewDate (x). GetHours ()//Get HoursNewDate (x). getminutes ()//Get minutesNewDate (x). tolocaledatestring ());//Convert to local date format, depending on the environment, output: July 04, 2017NewDate (x). toLocaleString ());//Convert to local date and time format, depending on the environment, output: July 04, 2017 morning 10:03:05
4. JavaScript does not have the functionality that the native provides but is often required to use
- Get the current day of the week by date
// parameter date Getweek (day) { = [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday ']; return Weekarr[day];} Getweek (New
- Get a Time + 1 hours, the number of hours directly plus 1 May overflow, so first converted to a Date object, and then use sethours to change the hours.
New Date (x). sethours (new Date (x). GetHours () +1,new Date (x). getminutes ());
- For the unified format, the return date is below 10 and needs to be preceded by 0.
function getfull (n) { return (n > 9?) ': ' 0 ') + N;} var x = Getfull (3); // Geneva var y = getfull (one); // One
- You often convert dates, so you add a function that transforms the format
Date.prototype.Format =function(FMT) {//Author:meizz varn \ { "m+": This. GetMonth () + 1,//Month"D+": This. GetDate (),//Day"H +": This. GetHours (),//hours"m+": This. getminutes (),//points"S+": This. getseconds (),//seconds"q+": Math.floor (( This. GetMonth () + 3)/3),//Quarterly"S": This. Getmilliseconds ()//milliseconds }; if(/(y+)/.test (FMT)) FMT = Fmt.replace (regexp.$1, ( This. getFullYear () + ""). substr (4-regexp.$1. length)); for(varKincho)if(NewRegExp ("(" + K + ")"). Test (FMT)) FMT = Fmt.replace (regexp.$1, (regexp.$1.length = = 1)? (O[k]): (("XX" + o[k]). substr ("" +o[k])); returnFMT; } //Call: varTime1 =NewDate (). Format ("Yyyy-mm-dd"); varTime2 =NewDate (). Format ("Yyyy-mm-dd hh:mm:ss");
JavaScript to play with date objects