Home > Web Front-end > JS Tutorial > Only 2 lines of code in javascript display the date and time effect in the specified format_time and date

Only 2 lines of code in javascript display the date and time effect in the specified format_time and date

WBOY
Release: 2016-05-16 18:01:46
Original
1054 people have browsed it

After studying at Blue Ideal for N years, today I will post something original for the first time because I have spent a lot of time solving this problem. The main reason is that the codes found on the Internet are either very cumbersome or cannot be universal or the format is only Fixed a few, so I specifically studied this problem, and finally optimized it to only 2 lines of code, which is very streamlined. It mainly uses JSON, regular and eval functions. If there are any questions, please feel free to correct me.
Thanks to zhanyuzai for the optimization. After testing the 2 lines of code, no problems were found. It has been updated now


[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]<script> /// <summary> /// 格式化显示日期时间 /// /// <param name="x">待显示的日期时间,例如new Date() /// <param name="y">需要显示的格式,例如yyyy-MM-dd hh:mm:ss 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>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template