The simplest and most flexible javascript date-to-string tool functions I have ever seen

Source: Internet
Author: User

The simplest and most flexible javascript date-to-string tool functions I have ever seen

We know that the Date object in javascript does not provide a Date Formatting Function. Converting a Date object to a format like 20:35:11 is a common requirement in projects. I recently saw a piece of code in our project, which is very short and shared here.

 

Date. prototype. format = function (format) {var o = {M +: this. getMonth () + 1, // monthd +: this. getDate (), // dayh +: this. getHours (), // hourm +: this. getMinutes (), // minutes +: this. getSeconds () // second}; 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. replac E (RegExp. $1, RegExp. $1. length = 1? O [k]: (00 + o [k]). substr (+ o [k]). length) ;}} return format ;};

 


This Code supports regular expressions, so we can flexibly create date formatting strings:

 

Var date = new Date (); alert (date. format (yyyy-MM -- dd hh: mm: ss ));


 

 

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.