Javascript with only two lines of code displays the date and time effect in the specified format _ time and date

Source: Internet
Author: User
Tags time and date
I spent a lot of time solving this problem, mainly because the code found on the network is either very cumbersome, or not common, or the format can only be fixed, so I have studied this problem specially, the final optimization is only two lines of code, which is very streamlined. I have been studying the blue ideal for N years. Today, I wrote my own originality for the first time, because I spent a lot of time solving this problem, mainly because the code found on the network is either very cumbersome, either it cannot be general or the format can only be fixed, so I have studied this issue and finally optimized it to only two lines of code, which is very streamlined. JSON, regular expression, and eval functions are mainly used. If you have any questions, please let us know.
Thanks to zhanyuzai for its optimization. After testing the two lines of code, no problem was found. Now it has been updated.

<Html> <body> script /// <summary> /// format the display Date and Time /// </summary> /// <param name = "x"> date and time to be displayed, for example, new Date () </param> // <param name = "y"> the format to be displayed, for example, yyyy-MM-dd hh: mm: ss </param> function date2str (x, y) {var z = {y: x. getFullYear (), M: x. getMonth () + 1, d: x. getDate (), h: x. getHours (), m: x. getMinutes (), s: x. getSeconds ()}; return y. replace (/(y + | M + | d + | h + | m + | s +)/g, function (v) {return (v. length> 1? "0": "") + eval ('z. '+ v. slice (-1). slice (-(v. length> 2? V. length: 2)});} alert (date2str (new Date (), "yyyy-M-d h: m: s ")); alert (date2str (new Date (), "yy-MMMM-d h: m: s"); script </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

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.