Now that I've introduced you to the cast of characters in temporal, it's time to show how to accomplish a programming task. I've personally always learned better by doing. So, I hope this will show you what you can do with the API. I've picked three tasks to walk through, an easy one, a medium one, and a complicated one. First, the easy one.
The easy task is to get the current time as a time stamp in milliseconds. This is the number one top voted question for the old JavaScript Date object on Stack Overflow. So, naturally we'll want to be able to do the same thing in temporal. First, we consider what type we have to use. A time stamp represents an exact time without regard to time zones. And so, we think back to the types that I mentioned. The type that corresponds to that exact time, no time zone, is instant.
The next thing, maybe it's kind of a meta thing to consider, is do we really want a timestamp in milliseconds, or will the instant object itself work just as well? I think going forward, as temporal gets wider adoption, I'd expect that numerical time stamps are going to be mainly necessary for interoperation with non JavaScript systems, not so much for JavaScript applications where we'll just use instant. But for the sake of this example, let's say that we do actually need a numerical timestamp. So, we know what type we need. Next, we need to know how to fill it with the current time.
We do this with the functions in the Now namespace. Any of these functions will give you the current date or time or time zone in the form of an instance of one of the temporal types. The ISO in the name means that the date is in the standard ISO calendar, and I'll talk more about calendars and what that means later. But since we need the current time as an Instant, we'll use the top one from this list, Temporal.Now.instant. Next, we need to figure out how to get a number of milliseconds since the Unix epoch from the instant.
So, this is a good time to talk about how do you get date and time info from your instances of temporal types. All the types have read-only properties that we can use to get this sort of information. So, for example, year is only on types that have calendars and also not on PlainMonthDay. Offset only exists on ZonedDateTime, and the epochNanoseconds and similar properties are only on the exact time types in ZonedDateTime. So, in our case, we need the epochMilliseconds property because that's the number of milliseconds since the Unix epoch of 1970, January 1st, midnight. So, we put all the information on the previous slides together into this one-liner here. We get the result of Temporal.Now.instant and examine its epochMilliseconds property to obtain a Unix timestamp in milliseconds.
And here's a possible output, depending on when you call the method.
Comments