js前端时间格式相互转换

6 篇文章 0 订阅

时间戳

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

获取当前时间

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

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

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

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

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

new Date().getTime()// 1572837781719
Date.now()// 1572837781719
Math.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’方法的结果。字符串形如‘2018-08-09T10:20:54.396Z’,转化为北京时间需要额外增加八个时区,我们需要取字符串前19位,然后把‘T’替换为空格,即是我们需要的时间格式。

时间格式转换为时间戳
new Date("2019-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时间)的毫秒数,如果该字符串无法识别,或者一些情况下,包含了不合法的日期数值(如:2015-02-31),则返回值为NaN

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Echo___Echo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值