Js formatting time _ javascript tips-js tutorial

Source: Internet
Author: User
Tags dateformat
This article mainly introduces the js time formatting method and summarizes the javascript time formatting method. Interested friends can refer to this article to share with you the javascript time formatting method, the content is as follows:
It can be said that it is an indispensable Javascript class library in Web projects. It can help you solve many client programming problems quickly. Below is a method for formatting 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] :("00"+ o[k]).substr((""+ o[k]).length));return format;}

The above code must be declared first and then used. Usage:

var d =new Date().format('yyyy-MM-dd');

Another method:

In Javascript, the Date object is Date. How do I output a Date object in a custom format?
We can tell you that the Date object has four built-in methods for output in string format:

  • 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 Date object in Javascript provides built-in methods to output these strings, these strings are not controlled by us. Therefore, if we need to customize a special format, so what should we do?
In a rush, jsjava built a dedicated class, dedicated to the daily entry pattern of the serial output, 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 (); // The DateFormat object is required for jsJava1.0. Do not make a mistake. applyPattern ("yyyy-MM-dd HH: mm: ss"); var date = new Date (,); var str = df. format (date); document. write (str); // The result is: 10:59:51

Through the above example, you can see that what you need to do is to specify the pattern. What does yyyy and MM in pattern mean? If you have learned how to format dates in Java, you should know that all placeholders have special functions. For example, y indicates year and yyyy indicates year of four numbers, for example, 1982, the following lists some special characters and their meanings supported by pattern (the following table is derived from the official Java documentation and has been modified as appropriate ):

G Era designator [url=]Text[/url] AD y Year [url=]Year[/url] 1996; 96 M Month in year [url=]Month[/url] July; Jul; 07 w Week in year [url=]Number[/url] 27 W Week in month [url=]Number[/url] 2 D Day in year [url=]Number[/url] 189 d Day in month [url=]Number[/url] 10 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 in day (1-24) [url=]Number[/url] 24 K Hour in am/pm (0-11) [url=]Number[/url] 0 h Hour in am/pm (1-12) [url=]Number[/url] 12 m Minute in hour [url=]Number[/url] 30 s Second in minute [url=]Number[/url] 55 S Millisecond [url=]Number[/url] 978

There are three other methods to share with you:

Method 1:

// Extend the Date to String // month (M), Day (d), hour (h), and minute (m) in the specified format), second (s), quarter (q) can use 1-2 placeholders, // year (y) can use 1-4 placeholders, Millisecond (S) only one placeholder (a number ranging from 1 to 3) can be used. // example: // (new Date ()). format ("yyyy-MM-dd hh: mm: ss. S ") => 08:09:04. 423 // (new Date ()). format ("yyyy-M-d h: m: s. S ") ==>. 18 Date. prototype. format = function (fmt) {// author: meizz 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 (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]): ("00" + 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");  

Method 2:

 
  
  

Method 3:

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($0) {          switch($0) {            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 ['Jan','Feb','Mar','Apr','May','Jun','Jul','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 > 99) 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);          }        });      }; 

I don't know how to choose a solution if there are more methods. However, we still need to study it carefully and select a solution for different problems. I hope you will like this article.

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.