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

  • 时间格式化以及指定时区(time&&timezone)已关闭评论
  • 138 次浏览
  • A+
所属分类:Web前端
摘要

工作中经常遇到按照指定格式的时间进行展示。可参考以下脚本逻辑满足需求

工作中经常遇到按照指定格式的时间进行展示。可参考以下脚本逻辑满足需求

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[k]) : (("00" + o[k]).substr(("" + o[k]).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);