Detailed examples of javascript date and time formatting

Source: Internet
Author: User
Tags current time getdate

Often encountered to format the timestamp, but are basically temporary need to write at any time, never collated, and today encountered the format of the timestamp, so recorded down, the need to directly take over to use.


No more nonsense, first of all the formatting methods posted to Everyone

var mydate = new Date ();

Mydate.getyear (); Get Current year (2-bit)

Mydate.getfullyear (); Get full year (4-bit, 1970-????)

Mydate.getmonth (); Get Current month (0-11, 0 for January)

Mydate.getdate (); Get the current day (1-31)

Mydate.getday (); Get Current week x (0-6, 0 for Sunday)

Mydate.gettime (); Gets the current time (number of milliseconds since 1970.1.1)

Mydate.gethours (); Get the current number of hours (0-23)

Mydate.getminutes (); Get the current number of minutes (0-59)

Mydate.getseconds (); Get the current number of seconds (0-59)

Mydate.getmilliseconds (); Get current number of milliseconds (0-999)

Mydate.tolocaledatestring (); Get Current date

var mytime=mydate.tolocaletimestring (); Get current time

Mydate.tolocalestring (); Get Date and time


can be said to be an indispensable JavaScript class library in a Web project that can help you quickly solve many of the problems with client programming, and post a way to format the time with JS.

  date.prototype.format =function (format)     {         var o = {         "m+"  :  This.getmonth () +1, //month "d+"  : this.getdate (),     //day "h+"  :  This.gethours (),    //hour "m+"  : this.getminutes (),  //minute "S+"  :  This.getseconds (),  //second "q+"  : math.floor ((This.getmonth () +3)/3),   //quarter "S"  : this.getmilliseconds ()  //millisecond         }          if (/(y+)/.test (format))  format=format.replace (RegExp.$1,  
        (This.getfullyear () + ""). substr (4- regexp.$1.length));         for (Var k in o) if (New RegExp ("+ k
 + ")"). Test (format)        format = format.replace (RegExp.$1,          REGEXP.$1.LENGTH==1? O[K]&NBSP:        
  ("+ o[k]"). substr (("+ o[k]). length);
        return format;     }

The above code must be declared before it is used. How to use:

  Var d =new date (). Format (' Yyyy-mm-dd ');   First Look code: date.prototype.format = function  (format)  {         format = format | |   ' Yyyy-mm-dd hh:mm:ss ';        var date = { 
           yyyy: this.getfullyear (),            yy: this.getyear (),             MM:  (This.getmonth ()  > 8 ?  '  :  ' 0 ')   +  (This.getmonth ()  + 1),            m:  this.getmonth ()  + 1,    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;DD:   (this.getdate ()  > 9 ?  '  :  ' 0 ')  + this.getdate (),     &NBSP;&NBSP;&NBSP;      d: this.getdate (),             hh: this.gethours (),            mm:   (this.getminutes ()  > 9 ?  '  :  ' 0 ')  + this.getminutes (),             ss:  (this.getseconds ()  > 9  ?  '  :  ' 0 ')  + this.getseconds (),             h: this.gethours (),            m:  this.getminutes (),            s:  This.getseconds ()         };        var  arr = format.match (/[a-za-z]+/g);        for  (var  i = 0; i  < arr.length; i++)  {             Format = format.replace (arr[i], date[arr[i]] | |   ');        }        return  format;   }

The specific parameters can look at the date object within the function.

For example: New Date ("2014-7-23 21:40:54"). Format ("Yyyy-mm-dd hh:mm:ss") results are: 2014-07-23 21:41:36;

For example: New Date ("2014-7-23 21:41:56"). Format ("Yyyy-m-dd hh:mm:ss") results are: 2014-7-23 21:42:39

Note the month in the above two examples, the format for mm corresponds to 07, for m corresponds to 7.

The two-letter representation is less than 10 front complement 0, and the single letter indicates that less than 10 does not complement 0. This setting can be supported for months, days, minutes, and seconds.

Date object is: Mon Sep 15:24:14 utc+0800 2015

<script type= "Text/javascript" > Date.prototype.format = function (format) { var o  = {  "m+"  : this.getmonth () +1, //month   "d+"  : this.getdate (),     //day   "h+"  : this.gethours (),    //hour    "m+"  : this.getminutes (),  //minute   "s+"  : this.getseconds (),  //second     "q+"  : math.floor (This.getmonth () +3)/3),   //quarter    "S"  :  This.getmilliseconds ()  //millisecond &nbsp}  if (/(y+)/.test (format))    {  format=
Format.replace (Regexp.$1, (this.getfullyear () + ""). substr (4 - regexp.$1.length)); &NBSP}     for (Var k in o)  {  if (New regexp ("" ("+ k  + ")"). Test (format))   {    format = format.replace (regexp.$1,regexp.$1. LENGTH==1&NBSP;?&NBSP;O[K] :  ("+ o[k]"). substr (("+ o[k]). length);
  }    return format;
} var d = new date ();
document.write (' Date object is: ');
document.write (d);
Var str = d.format (' Yyyy-mm-dd ');
Var today = document.getelementbyid ("Todaybutton");
today.value = str; </script>

Example 3

<mce:script language= "JavaScript"  type= "Text/javascript" ><!--       /**        *  extended to Date, converting  Date  to string   in the specified format       *  Month (m), Day (d), 12 hours (h), 24 hours (h), minutes (M), SEC (s), Week (E), quarter (q)   can be used  1-2  Placeholders         *  years (y) can be used with  1-4  placeholders, milliseconds (s) only with  1  placeholders (yes

 1-3  digits)         * eg:        *  (New date ()). Pattern ("Yyyy-mm-dd hh:mm:ss. S ")  ==> 2006-07-02 08:09:04.423        *  (new  Date ()). Pattern ("Yyyy-mm-dd e hh:mm:ss")  ==> 2009-03-10  two  20:09:04         *  (New date ()). Pattern ("Yyyy-mm-dd ee hh:mm:ss")   ==> 2009-03-10  Tuesday &NBSP;08:09:04&NBSP;&Nbsp;      *  (New date ()). Pattern ("Yyyy-mm-dd eee hh:mm:ss")  = => 2009-03-10  Tuesday  08:09:04        *  (New date ())

. Pattern ("YYYY-M-D&NBSP;H:M:S.S")  ==> 2006-7-2 8:9:4.18        */         date.prototype.pattern=function (FMT)  {               var o = {                "m+"  : this.getmonth () +1, // Month                "d+"  : this.getdate ( ),  //day                "h+"  :  This.gethours ()%12 == 0 ? 12 : this.gethours ()%12, //hours                 "h+"  : this.gethours (),  //hour                 "m+"  : this.getminutes (),  //points                "S+"  : this.getseconds (),  //sec                "q+"  :  Math.floor ((This.getmonth () +3)/3),  //quarterly                 "S"  : this.getmilliseconds ()  //Ms                };               var week = {               "0"  :  "/u65e5",               "1" &nbsp: &nbSP; " /u4e00 ",              " 2 " : "/u4e8c " ,               "3"  :  "/u4e09",                "4"  :  "/u56db",                "5"  :  "/u4e94",                "6"  :  "/u516d"               };               if (/(y+)/.test (FMT)) {                   fmt=fmt.replace (regexp.$1,  (this.getfullyear () + ""). substr (4 -  regexp.$1.length);              }              if (/(e+)/.test (FMT)) {                   fmt=fmt.replace ( regexp.$1,  (regexp.$1.length>1)  ?  (regexp.$1.length>2 ?  "/u661f/u671f" &NBSP;:

  "/u5468")  :  "") +week[this.getday () + ""]);              }              for (Var  k in o) {                   if (New regexp ("+ k +")). Test (FMT) {                       fmt =  Fmt.replace (regexp.$1,  (regexp.$1.length==1)  ?  (O[k])  :  (("+ o[k]"). substr (("" + o[k]). Length));                  }               }               return fmt;          }              var date =  new date ();       Window.alert (Date.pattern ("Yyyy-MM-dd hh:mm:ss")

));  --></mce:script>

 

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.