js Date时区矫正

JavaScript09

js Date时区矫正,第1张

前言:有时候后端返回给前端的时间格式是这种的

        该时间格式为UTC格式,"+00:00","+"代表是东边的时区,当"+"变成"-"时,代表是西边的时区,后面紧接着的两个数字代表的是具体那个时区,如"+08"代表东八区,":"后的两个数代表和伦敦协调时偏差多少分钟。

        将该时间格式改成"YYYY-mm-dd HH:MM:SS"等格式,则需要处理后端返回时区与本时区时间的偏差。js的Date对象提供getTimezoneOffset函数,用于获取本时区与伦敦协调时的时间差,返回数值的单位是分钟。

        Date对象的toLocaleDateString函数,在PC端和移动端有差别,在安卓移动端会比PC端的返回值多"上午"、"下午"等。

        没有直接使用new Date(value)来获取日期,是因为在IOS系统下,年月日的分隔符只有是"/"的字符串(如"2019/09/09")用new Date(string)得到正确的日期。

        还有另一种格式GMT,相较于UTC格式,GMT没有那么精确,不能具体到毫秒。

        以下内容为追加GMT格式转换

参考:

    JS操作时间 - UNIX时间戳简单介绍  -  阿胜4K

    世界协调时间(UTC)

    MDN Date

一般的处理方式是在前台通过JS控制,JS控制显示时间的代码如下,各种不同的显示方式:

[javascript]

function Clock() {

var date = new Date()

this.year = date.getFullYear()

this.month = date.getMonth() + 1

this.date = date.getDate()

this.day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[date.getDay()]

this.hour = date.getHours() <10 ? "0" + date.getHours() : date.getHours()

this.minute = date.getMinutes() <10 ? "0" + date.getMinutes() : date.getMinutes()

this.second = date.getSeconds() <10 ? "0" + date.getSeconds() : date.getSeconds()

this.toString = function() {

return "现在是:" + this.year + "年" + this.month + "月" + this.date + "日 " + this.hour + ":" + this.minute + ":" + this.second + " " + this.day

}//现在是<span id="clock">现在是:2013年3月6日 13:54:17 星期三</span>

[javascript]

<span></span>

this.toSimpleDate = function() {

return this.year + "-" + this.month + "-" + this.date

}//2013-03-06

this.toDetailDate = function() {

return this.year + "-" + this.month + "-" + this.date + " " + this.hour + ":" + this.minute + ":" + this.second

}//2013-03-06 13:45:43

this.display = function(ele) {

var clock = new Clock()

ele.innerHTML = clock.toString()//显示方式调用

window.setTimeout(function() {clock.display(ele)}, 1000)

}

}

<script language="JavaScript">

//日期

var now = new Date()//获取系统日期

var yy = now.getYear()//截取年

var mm = now.getMonth()//截取月

var dd = now.getDay()//截取日

//取时间

var hh = now.getHours()//截取小时

var mm = now.getMinutes()//截取分钟

var ss = now.getTime() % 60000//获取时间,因为系统中时间是以毫秒计算的,

所以秒要通过余60000得到。

ss= (ss - (ss % 1000)) / 1000//然后,将得到的毫秒数再处理成秒

var clock = hh+':'//将得到的各个部分连接成一个日期时间

if (mm <10) clock += '0'//字符串

clock += mm+':'

if (ss <10) clock += '0'

clock += ss

</script>