How to parse string date to something friendly

Hello there,

I always get confused on how to parse date strings to something readable.

I’ve the following string:

"2020-07-02T17:06:52.739Z"

How do I parse this string in JavaScript to be something like: June 17, 2020. (Or something like this… friendly and readable);

Hello,

What about this ?
const str ="2020-07-02T17:06:52.739Z";

JS: new Date(str).toDateString() //"Fri Jul 03 2020"
or
moment.js: moment(str).format('MMMM DD,YYYY'); //"July 03,2020"

Convert to a date object if it isn’t already that:

let d = new Date("2020-07-02T17:06:52.739Z")

You can use toLocaleDateString

d.toLocaleDateString()

This gives “Thu Jul 02 2020”. The function takes two arguments: a locale, and options. The options are described here. Look at some examples, it’s quite robust, you generally only need that (and the default is normally fine).

You can use a library like Moment (though note that Moment has several fundamental issues and there are better options, it was just the only good option for a very long time), but for what you need that’s a very heavyweight option.

@Annestezia @DanCouper

I should have explained a little bit more. My bad.

What I’m actually doing is mapping over an object in React… Something like this:

users.map(user => {
  return(
    <span>{user.createdAt}</span> // this returns the date string
  )
})

Even though your solutions are pretty good and answered my question, I can’t use user.createdAt.toDateString() or user.createdAt.toLocaleDateString() because I get TypeError: user.createdAt.toLocaleDateString is not a function

You have a property that is a date string. Strings don’t have a toLocaleDateString property. Convert it to a date like new Date(theDateString), then you can apply functions that are designed to work on Date objects. You can use it just fine, there is nothing in your code that prevents you doing this.

The issue is that if you just don’t bother converting it to a Date object, JavaScript cannot apply any date-specific formatter functions: attempting to run a function that doesn’t exist (ie String.prototype.toLocaleDateString()) will, naturally, generate an error.

1 Like

Awesome explanation! Thanks

1 Like