JavaScript time conversion method

藏色散人
Release: 2023-01-05 16:11:43
Original
2903 people have browsed it

javascript时间转换的方法:首先创建一个util.js文件;然后在里面重新封装一下Date的format方法;最后通过“new Date().Format()”方式调用实现时间转换即可。

JavaScript time conversion method

本文操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

javascript时间转换

创建一个util.js文件,在里面重新封装一下Date的format方法:

//Date的prototype 属性可以向对象添加属性和方法。 Date.prototype.Format = function(fmt) { var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours() % 12 === 0 ? 12 : this.getHours() % 12, //小时 "H+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; var week = { "0": "\u65e5", "1": "\u4e00", "2": "\u4e8c", "3": "\u4e09", "4": "\u56db", "5": "\u4e94", "6": "\u516d" }; if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } if (/(E+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]); } 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; };
Copy after login

具体调用的时候就可以变得很方便,想要什么格式就可以形成什么格式,例如 年月日 星期几 时分秒,做个简单的例子,如果有哪里看不明白可以评论,我看见会给你解释的。

let date = new Date().Format("yyyy年MM月dd日\tEEE\tHH:mm:ss"); $("#date-now").html(date);
Copy after login

【推荐学习:javascript高级教程

The above is the detailed content of JavaScript time conversion method. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!