JavaScript only 2 lines of code display date Time effect _ time date in the specified format

Source: Internet
Author: User
Tags eval
In the blue ideal to learn n years, the first time today to send a point of their own original, because I have spent a lot of time to solve the problem, mainly on the network found on the code is very cumbersome, or can not be generic or format can only be fixed a few, so I specialize in this issue has been studied, and finally optimized to only 2 lines of code, very concise. The main thing is to use the JSON, regular, and eval functions, and if you have any questions, you're welcome to correct them.
Thanks to Zhanyuzai's optimization, tested 2 lines of code did not find the problem, has now been updated over
<ptml> <body> <script>///<summary>/// Format display date time///</summary>///<param name= "x" > The datetime to be displayed, such as new Date () </param>///<param name= "Y" > The format that needs to be displayed, such as 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 All selected note: If you need to introduce external JS need to refresh to perform]
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.