Formatting date in ES6

I am formatting the date, not with pulses or any other library, just pure JS. And I want to know if there is a way to simplify this with ES6

let currentDate = new Date(); 

const videosInformation = {
  time: currentDate.getHours() + ':' + currentDate.getMinutes(),
  date: (currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear(),
  gameId: Math.floor((Math.random() * 5000) + 1)
};

      

I saw that in the DOM you use something like renderSomething={`something: ${someObj}`}

so you don't need to do renderSomething={"something: " + {someObj}}

is there something I should use to create a format like this?

+3


source to share


1 answer


There is nothing in ES2015 that added something like strftime

no. There's an ECMAScript internationalization specification ecma-402 that allows you to localize time:

let [date, time] = new Date().toLocaleString('en-US').split(', ');

const videosInformation = {
  time,
  date,
  gameId: Math.floor((Math.random() * 5000) + 1)
};

      

Which would give you localized US on 8/4/2015 and 5:29:19 PM Or if you really want 24 hour time:



new Date().toLocaleString('en-US', {hour12: false})

      

Then you can substring for the time if you want to strip out the seconds.

You can find out more about date and time in the MDT docs .

+14


source







All Articles