In JavaScript/Typescript, it is possible to convert a UTC time in ISO 8601 format to a date string in the "yyyy-mm-dd" format using built-in methods. In this blog post, we will discuss how to do this conversion in JavaScript.
Code
const utcTimeString = "2023-07-06T01:00:00.000Z";
const date = new Date(utcTimeString);
const yyyyMMdd = date.toISOString().slice(0, 10);
console.log(yyyyMMdd); // outputs "2023-07-06"
In the example code above, we first create a new Date
object from the UTC time string using new Date(utcTimeString)
. We then call toISOString()
on the Date
object to get a string in ISO 8601 format, which looks like this: "2023-07-06T01:00:00.000Z".
Finally, we call the slice()
method to extract the first 10 characters of the ISO string, which represent the year, month, and day in "yyyy-mm-dd" format. The resulting string is stored in the yyyyMMdd
variable.
What does the format T00:00:00.000Z mean?
The format "T00:00:00.000Z" represents a specific time in the ISO 8601 format, which is used to represent date and time information in a standardized way.
The "T" in the format separates the date and time components of the string. "00:00:00.000" represents the time component of the string, which is in the format "hours:minutes:seconds.milliseconds". In this case, the time is set to midnight, i.e., 00 hours, 00 minutes, and 00 seconds, with 000 milliseconds.
The "Z" at the end of the string indicates that the time is in Coordinated Universal Time (UTC), which is a standardized time zone used as a reference for international timekeeping.
So, the format "T00:00:00.000Z" represents the exact moment of midnight (00:00:00) in UTC time.
Conclusion
By using the built-in Date object, toISOString() method, and slice() method, we can easily extract the date component from a UTC time string. This can be useful when working with APIs that return date and time information in UTC format, or when displaying date information in a specific format in a web application.