JavaScript新的时间全局对象Temporal

背景

ECMA TC39临时提案正在努力为JavaScript语言编写更好的日期和时间API。 它目前处于TC39流程的第二阶段。

Temporal将成为一个新的全局对象,它的形式是顶级名称空间(如Math)。 它公开了许多不同类型的对象,包括Temporal.Absolute,Temporal.DateTime,Temporal.Date,Temporal.Time,Temporal.TimeZone等。 Temporal Cookbook展示了许多“食谱”,并举例说明了如何在不同的场景中使用这些对象。

您今天可以通过实验性的polyfill尝试Temporal。 请尝试但不要在生产中使用它!

一些使用场景和示例代码

最基础场景

  • 当前日期和时间
/**
 * Get the current date in JavaScript
 * This is a popular question on Stack Overflow for dates in JS
 * https://stackoverflow.com/questions/1531093/how-do-i-get-the-current-date-in-javascript
 *
 */

const date = Temporal.now.date(); // Gets the current date
date.toString(); // returns the date in ISO 8601 date format

// If you additionally want the time:
Temporal.now.dateTime().toString(); // date and time in ISO 8601 format
  • Unix时间戳
/**
 * Get a (Unix) timestamp in JavaScript
 * This is the No.1 voted question on Stack Overflow for dates in JS
 * https://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript
 *
 */

const timeStamp = Temporal.now.absolute();

// Timestamp in Milliseconds
timeStamp.getEpochMilliseconds();
// Timestamp in Seconds
timeStamp.getEpochSeconds();

在时间类型和旧日期之间转换

  • 遗留日期绝对值
const legacyDate = new Date(
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值