600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > js前端时间格式相互转换

js前端时间格式相互转换

时间:2020-06-27 06:14:23

相关推荐

js前端时间格式相互转换

时间戳

时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

获取当前时间

获取当前时间(格林威治时间)

new Date()// Mon Nov 04 11:18:38 GMT+0800 (中国标准时间)

获取当前时间戳,以秒s为单位

Math.round(new Date() / 1000)// 1572837688

获取当前时间戳,以毫秒ms为单位

new Date().getTime()// 1572837781719Date.now()// 1572837781719Math.round(new Date())// 1572837781719

时间戳转指定时间格式

***date 要转换的时间戳*format 时间格式**/*时间戳转指定时间格式*@method formatTime*@param{number}date 时间戳* @param{String}format 时间格式*@return {String} */formatTime = (date, format) => {var timeformat = new Date(date)var tf = function (i) {return (i < 10 ? '0' : '') + i }return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {switch (a) {case 'yyyy':return tf(timeformat.getFullYear())case 'MM':return tf(timeformat.getMonth() + 1)case 'mm':return tf(timeformat.getMinutes())case 'dd':return tf(timeformat.getDate())case 'HH':return tf(timeformat.getHours())case 'ss':return tf(timeformat.getSeconds())}})}

在网上又找到了另一种方法,觉得很简洁,拿来看看

function time(time = +new Date()) {var date = new Date(time + 8 * 3600 * 1000);return date.toJSON().substr(0, 19).replace('T', ' ').replace(/-/g, '.');}

Date的‘toJSON’方法返回格林威治时间的JSON格式字符串,实际是使用‘toISOString’方法的结果。字符串形如‘-08-09T10:20:54.396Z’,转化为北京时间需要额外增加八个时区,我们需要取字符串前19位,然后把‘T’替换为空格,即是我们需要的时间格式。

时间格式转换为时间戳

new Date("-11-04 11:03:35").getTime()//1572836615000

Date.prototype.toISOString()

toISOString()方法返回一个ISO(ISO 8601 Extended Format)格式的字符串:YYYY-MM-DDTHH:mm:ss.sssZ。时区总是UTC(协调世界时),加一个后缀“Z”标识。

语法:dateObj.toISOString()

Date.parse()

Date.parse()方法解析一个表示某个日期的字符串,并返回从1970-1-1 00:00:00 UTC 到该日期对象(该日期对象的UTC时间)的毫秒数,如果该字符串无法识别,或者一些情况下,包含了不合法的日期数值(如:-02-31),则返回值为NaN。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。