琳媛 发表于 2023-9-21 02:45:56

时间格式化以及指定时区(time&&timezone)

工作中经常遇到按照指定格式的时间进行展示。可参考以下脚本逻辑满足需求
Date.prototype.PtTimeByFormat = function (fmt){
    var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o) : (("00" + o).substr(("" + o).length)));
    return fmt;
}
//日期格式 "yyyy-MM-dd"|"yyyy-MM-dd HH:mm:ss"
var ptTime = new Date().PtTimeByFormat("yyyy-MM-dd HH:mm:ss");工作中会遇到指定时区的需求,不管从全球哪个国家的用户访问产品,都以指定时区来展示时间。
var timezone = 9;//定义时区
var offset_GMT = new Date().getTimezoneOffset();
var nowDate = new Date().getTime();
var targetDate = new Date(nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000);
来源:https://www.cnblogs.com/yangzhihui/p/time_timezone.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 时间格式化以及指定时区(time&&timezone)