时间字符串和时间戳的转换

时间字符串转换为时间戳方法

1.new Date().getTime()

new Date('2021-12-14 10:10:00').getTime()  // 1639447800000

2.Date.parse()

Date.parse('2021-12-14 10:10:00')  // 1639447800000

封装方法

conversionTime(date) {
    let t = ''
    if (date === '') {
      return ''
    }
    if (!date) {
      const oDate = new Date()
      t = Date.parse(oDate)
    } else {
      // 兼容360、ie浏览器, 360、ie只支持'/'时间格式
      typeof date === 'string' && date.indexOf('-') !== -1 && (date = date.replace(/-/g, '/'))
      const oDate = new Date(date)
      t = Date.parse(oDate)
    }
    return t
  }

时间戳转换为字符串

let time = ‘1639440000’
Let timeLength = time.length
Let timeStr = null
if (timeLength === 10) {
    timeStr = new Date(time * 1000)
} else if (timeLength === 13) {
    timeStr = new Date(time)
} else if (timeLength === 19) {
    timeStr = new Date(time)
}
let year = timeStr .getFullYear()
let month = timeStr .getMonth() + 1
let day = timeStr .getDate()
let hour = timeStr .getHours()
let minute = timeStr .getMinutes()
let second = timeStr .getSeconds()
if (month < 10) {
    month = '0' + month
}
if (day < 10) {
   day = '0' + day
}
if (hour < 10) {
    hour = '0' + hour
}
if (minute < 10) {
    minute = '0' + minute
}
if (second < 10) {
    second = '0' + second
}
return `${year}-${month}-${day} ${hour}:${minute}:${second}`

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将时间字符串转换时间戳,有多种方法可以实现。引用提供了JavaScript的示例代码,可以根据时间字符串的长度使用不同的方式来获取时间戳。如果时间字符串的长度为10,表示时间戳是以秒为单位的,可以将时间字符串乘以1000转换为以毫秒为单位的时间戳。如果时间字符串的长度为13或19,表示时间戳已经是以毫秒为单位的,可以直接使用时间字符串作为时间戳。然后,可以使用JavaScript的Date对象的方法来获取年、月、日、小时、分钟和秒。如果月、日、小时、分钟、秒的值小于10,则在前面补零。最后,将获取到的年、月、日、小时、分钟和秒拼接成字符串返回即可。 引用是Java的示例代码,可以使用DateTimeUtils类的toLongDateStr方法将时间字符串转换时间戳。这个方法接受一个时间字符串作为参数,并返回一个时间戳字符串。 引用提供了一个封装方法conversionTime,可以将时间字符串转换时间戳。这个方法首先判断传入的时间字符串是否为空,如果为空则返回空字符串。然后,判断传入的时间字符串的格式,如果是以'-'分隔的日期格式,则将'-'替换为'/',以兼容360和IE浏览器。接着,将时间字符串转换为Date对象,并使用Date.parse方法将Date对象转换时间戳。最后,返回时间戳。 综上所述,要将时间字符串转换时间戳,可以根据自己所用的编程语言选择相应的方法实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值