JS Date format Conversion method

Source: Internet
Author: User

JS Date format Conversion method

1. Convert the date to the specified format: for example, when you convert to a month or day, this format: Yyyy-mm-dd hh:mm:ss or YYYY-MM-DD. Of course the method is online, just summarized below.

You can add the following method to the date prototype:

Date.prototype.format =function(FMT) {varo = {         "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;} 

For example, we can invoke the following:

var time1 = new Date (). Format ("Yyyy-mm-dd hh:mm:ss");
Console.log (TIME1);

Run as follows:

It can also be converted into a "month and day" format

var time2 = new Date (). Format ("Yyyy-mm-dd");
Console.log (time2);

Run as follows:

2. Convert the specified date to the "Month Day" format, with the following code:

var oldtime = (New Date ("2012/12/25 20:11:11")). GetTime ();
var curtime = new Date (oldtime). Format ("Yyyy-mm-dd");
Console.log (Curtime);

Run as follows:

3. Convert the timestamp to the format of month Day .

For example, the following code:  

var da = 1402233166999;
da = new Date (DA);
var year = da.getfullyear () + ' years ';
var month = Da.getmonth () +1+ ' month ';
var date = da.getdate () + ' Day ';
Console.log ([Year,month,date].join ('-')]);

Run as follows:

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.