The method of JS format time _javascript Skill

Source: Internet
Author: User
Tags dateformat getdate string format

This article for everyone to share the JavaScript time format of the method, to share with you for your reference, the specific content as follows
Can be said to be a Web project indispensable JavaScript class library, it can help you quickly solve the client programming many problems, below posted a JS format Time method.

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]:
("+ o[k]"). substr (("" "+ o[k]). length);
return format;
}

The above code must first be declared and then used. How to use:

var d =new Date (). Format (' Yyyy-mm-dd ');

Another method:

In JavaScript, date objects are dates, so how do you export a Date object in a custom format?
You can now tell you that the Date object has four built-in methods for output in string format, respectively:

    • 1) togmtstring, display a date in GMT format
    • 2) tolocalestring, display a date in the local operating system format
    • 3) tolocaledatestring, display the date part of a Date object in local format
    • 4) tolocaletimestring, display the time part of a Date object in local format

Although the JavaScript Date object has built-in methods for the output as strings, these strings are not in our control format, so what if we need a special format that we customize?
Don't worry, Jsjava provides a dedicated class that specifically formats the string output for a date, you can download Jsjava-2.0.zip, introduce the src/jsjava/text/dateformat.js, or directly introduce jslib/ Jsjava-2.0.js, the sample code is as follows:

var df=new simpledateformat ();//jsjava1.0 need to use DateFormat object, do not mistake is 
df.applypattern ("Yyyy-mm-dd HH:mm:ss"); 
var date=new date (2015,12,18,10,59,51); 
var str=df.format (date); 
document.write (str);//Display result: 2015-12-18 10:59:51

You can see from the above example, you need to do is to specify pattern, then the pattern of yyyy, MM and so what mean? If you have studied the date format of Java, then you should know that these are placeholders that have special functions, such as Y for years, yyyy for four digits, such as 1982, Here are some of the special characters supported in pattern and their meanings (the table below is from the official Java documentation and modified appropriately):

G Era designator [Url=]text[/url] AD 
y [Url=]year[/url] 1996; M Month in the year 
[Url=]month[/url] July; June June; 
w Week in [Url=]number[/url]-Week in 
month [Url=]number[/url] 2 D ' Day in year 
[Url=]number[/url] 189 
D Day in month [Url=]number[/url] ten 
F day of week in month [Url=]number[/url] 2 
E day in week [url=]text[ /URL] Tuesday; Tue 
a am/pm marker [Url=]text[/url] PM 
H Hour in Day (0-23) [Url=]number[/url] 0 
k Hour by day (1-24) [url=] Number[/url] 
K Hour in am/pm (0-11) [Url=]number[/url] 0 
H Hour in am/pm (1-12) [Url=]number[/url] 
m Minute in hour [Url=]number[/url] a 
Second in Minute [Url=]number[/url]- 
millisecond [Url=]number[/url] 9 78

There are also three ways to share:

The first method of

:

An extension to date that converts date to a string/month (M) in the specified format, days (d), hours (h), minutes (M), seconds (s), quarter (q) can be used with 1-2 placeholders,//year (Y) can be 1-4 placeholders, milliseconds (s) can only use 1 placeholders Character (1-3 digits)//Example://(New Date ()). Format ("Yyyy-mm-dd hh:mm:ss. S ") ==> 2006-07-02 08:09:04.423//(New Date ()).  Format ("yyyy-m-d h:m:s.s") ==> 2006-7-2 8:9:4.18 Date.prototype.Format = function (FMT) {//author:meizz var o          = {"m+": This.getmonth () +1,//month "d+": this.getdate (),//day "h+": this.gethours (), Hours "m+": this.getminutes (),//"s+": This.getseconds (),//sec "q+": Math.floor (this.ge  
 Tmonth () +3)/3),//Quarter "S": this.getmilliseconds ()//millisecond};  
 if (/(y+)/.test (FMT)) Fmt=fmt.replace (Regexp.$1, (this.getfullyear () + ""). substr (4-regexp.$1.length)); 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; 
 }

Call Method:

var time1 = new Date (). Format ("Yyyy-mm-dd HH:mm:ss");    
var time2 = new Date (). Format ("Yyyy-mm-dd");  

The second method:

<mce:script language= "javascript" type= "Text/javascript" ><!--/** * Extension of date, converting date to a string * in a specified format   
 Month (m), Day (d), 12 hours (h), 24 hours (h), minutes (m), seconds (s), Week (E), quarter (q) can use 1-2 placeholder * year (y) can use 1-4 placeholders, milliseconds (s) can only use 1 placeholders (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 II 20:09:04 * (new Date ()). Pattern ("Yyyy-mm-dd EE hh:mm:ss") ==> 2009-03-10 Tuesday 08:09:04 * (new Date ()). Pattern ("Yyyy-mm-dd EEE hh    
: Mm:ss ") ==> 2009-03-10 Tuesday 08:09:04 * (New Date ()). Pattern (" yyyy-m-d 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,//hr "h+": this.gethours (),//Hour "m+": this.getminutes (),//"s+": this. Getseconds (),//sec "q+": Math.floor (this.geTmonth () +3)/3),//Quarter "S": this.getmilliseconds ()//millisecond}; var week = {"0": "/u65e5", "1": "/u4e00", "2": "/u4e8c", "3": "/u4e09", "4": "/u5     
  6db "," 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>2?)     
  "/u661f/u671f": "/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>

  A third method:

Date.prototype.format = function (mask) {var d = this;   
   
    var zeroize = function (value, length) {if (!length) length = 2;   
   
    Value = String (value);   
   
    for (var i = 0, zeros = '; i < (length-value.length); i++) {zeros = = ' 0 ';   
   
  return zeros + value;    
   
  }; return Mask.replace (/"[^"]* "|") [^ ']* ' |/b (?:d {1,4}|m{1,4}|yy (?: yy)? | ([HHMSTT])/1?| [Llz])   
   
      /b/g, function ($) {switch ($) {case ' d ': return D.getdate ();   
   
      Case ' DD ': Return Zeroize (D.getdate ());   
   
      Case ' DDD ': return [' Sun ', ' Mon ', ' Tue ', ' Wed ', ' Thr ', ' Fri ', ' Sat '][d.getday ()];   
   
      Case ' dddd ': return [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday '][d.getday ()];   
   
      Case ' M ': Return D.getmonth () + 1;   
   
      Case ' MM ': Return Zeroize (D.getmonth () + 1); Case ' MMM ': return [' Out of the ', ' Feb ', ' Mar ', ' Apr ', ' may ', ' June ', ' may ', ' Aug ', ' Sep ', ' Oct ', ' Nov ', ' Dec '][d.getmonth ()]; Case ' MMMM ': return [' January ', ' February ', ' March ', ' April ', ' may ', ' June ', ' July ', ' August ', ' September ', ' October ', '   
   
      November ', ' December '][d.getmonth ()];   
   
      Case ' yy ': Return String (D.getfullyear ()). substr (2);   
   
      Case ' yyyy ': return D.getfullyear (); Case ' H ': return d.gethours ()% 12 | |   
   
      12;   
   
      Case ' hh ': Return Zeroize (d.gethours ()% 12 | | 12);   
   
      Case ' H ': return d.gethours ();   
   
      Case ' HH ': Return Zeroize (D.gethours ());   
   
      Case ' m ': return D.getminutes ();   
   
      Case ' mm ': Return Zeroize (D.getminutes ());   
   
      Case ' s ': return D.getseconds ();   
   
      Case ' SS ': Return Zeroize (D.getseconds ());   
   
      Case ' l ': Return Zeroize (D.getmilliseconds (), 3);   
   
          Case ' L ': var m = d.getmilliseconds ();   
   
          if (M >) m = Math.Round (M/10);   
   
      Return Zeroize (m); Case ' TT ': Return d.gethours () < 12? ' Am ': ' PM'; Case ' TT ': Return d.gethours () < 12?   
   
      ' AM ': ' PM ';   
   
      Case ' Z ': Return d.toutcstring (). Match (/[a-z]+$/);   
   
    Return quoted strings with the surrounding quotes removed Default:return $0.substr (1, $0.length-2);   
   
}   
   
  });  };

Method more than one, do not know how to choose, but still rely on everyone to study carefully, for different problems to choose solutions, I hope you like this 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.