How to Convert a Date String into a Human-Readable Format
Publikováno: 25.5.2020
I’ll be the first to admit that I’m writing this article, in part, because it’s something I look up often and want to be able to find it next time. Formatting a date string that you get from an API in JavaScript can take many shapes — anything from loading all of Moment.js to have very finite control, or just using a couple of lines to update it. This article is not meant to be comprehensive, but aims to show … Read article “How to Convert a Date String into a Human-Readable Format”
The post How to Convert a Date String into a Human-Readable Format appeared first on CSS-Tricks.
I’ll be the first to admit that I’m writing this article, in part, because it’s something I look up often and want to be able to find it next time. Formatting a date string that you get from an API in JavaScript can take many shapes — anything from loading all of Moment.js to have very finite control, or just using a couple of lines to update it. This article is not meant to be comprehensive, but aims to show the most common path of human legibility.
UTC is an extremely common date format. You can generally recognize it by the Z
at the end of the string. Here’s an example: 2020-05-25T04:00:00Z
. When I bring data in from an API, it’s typically in UTC format.
If I wanted to format the above string in a more readable format, say May 25, 2020, I would do this:
const dateString = '2020-05-14T04:00:00Z'
const formatDate = (date) => {
const options = { year: "numeric", month: "long", day: "numeric" }
return new Date(date).toLocaleDateString(undefined, options)
}
Here’s what I’m doing…
First, I’m passing in options for how I want the output to be formatted. There are many, many other options we could pass in there to format the date in different ways. I’m just showing a fairly common example.
const options = { year: "numeric", month: "long", day: "numeric" }
Next, I’m creating a new Date
instance that represents a single moment in time in a platform-independent format.
return new Date(date)
Finally, I’m using the .toLocaleDateString()
method to apply the formatting options.
return new Date(date).toLocaleDateString(undefined, options)
Note that I passed in undefined
. Not defining the value in this case means the time will be represented by whatever the default locale is. You can also set it to be a certain area/language. Or, for apps and sites that are internationalized, you can pass in what the user has selected (e.g. 'en-US'
for the United States, 'de-DE'
for Germany, and so forth). There’s a nice npm package that includes list of more locales and their codes.
Hope that helps you get started! And high fives to future Sarah for not having to look this up again in multiple places. 🤚
The post How to Convert a Date String into a Human-Readable Format appeared first on CSS-Tricks.