背景
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(