【问题标题】:How do I change a string value to a timestamp? Javascript React-Native如何将字符串值更改为时间戳? Javascript React-Native
【发布时间】:2021-08-09 12:43:54
【问题描述】:

我有一个开始日期作业,我想添加用户输入的天数。 (作为工作的持续时间) 我想通过将持续时间添加到开始日期来找出工作的最后日期。

开始日期保存为时间戳,而持续时间保存为字符串。

我可以将两者相加并得到一个最终值作为时间戳吗?

【问题讨论】:

  • “开始日期是……时间戳”是什么意思?您是指像“2021 年 8 月 23 日”这样的字符串还是像 1629640800000 这样的数字?两者都是timestamps
  • @RobG 一个像 1629640800000 这样的数字。
  • 时间戳已经被视为Number,您甚至可以尝试console.log(typeof Date.now())进行验证。只需将字符串也更改为数字(您可以使用ParseInt

标签: javascript react-native time


【解决方案1】:

首先将时间戳转换为日期对象,然后在日期中添加持续时间,然后再次将其转换回时间戳

示例

const timestamp = 1629640800000

const date = new Date(timestamp * 1000);
console.log(date) // Wed Apr 06 53611 13:00:00

const hours = date.getHours() 
console.log(hours) // 13

//suppose you want to add 4 hours in the existing date-time

date.setHours(hours + 4);
console.log(date) // Wed Apr 06 53611 17:00:00

// now converting back to timestamp

Date.parse(date)
console.log(date) // 1629640814400000

【讨论】:

  • 53611 年 4 月 6 日表示时间值可能不应乘以 1,000。 Date.parse(date) 效率很低,应该是date.getTime() 或者date.valueOf() 或者只是+date
猜你喜欢
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
  • 2021-11-19
  • 1970-01-01
  • 2017-07-27
  • 2021-11-18
  • 1970-01-01
相关资源
最近更新 更多