Home > Web Front-end > JS Tutorial > How to convert time in javascript

How to convert time in javascript

coldplay.xixi
Release: 2023-01-04 09:34:21
Original
3034 people have browsed it

javascript转换时间的方法:创建一个【util.js】文件,在里面重新封装一下Date的format方法,代码为【let date = new Date().Format("yyyy年M月dd日\tEEE\tHH:mm:ss")】。

How to convert time in javascript

本教程操作环境: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 How to convert time in javascript. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template