Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format date in ES6

I am formatting a Date, with not momentjs 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 have to do renderSomething={"something: " + {someObj}}

is there something I should use to do that kind of format?

like image 856
Non Avatar asked Aug 03 '15 16:08

Non


People also ask

What date format is DD MMM YYYY JavaScript?

There is no native format in JavaScript for” dd-mmm-yyyy”. To get the date format “dd-mmm-yyyy”, we are going to use regular expression in JavaScript.

How do you format a date?

Many people get confused about how to write dates with commas, so here is a rule of thumb: in the month-day-year format (used in the United States), place commas after the day and year. In the day-month-year format (used in the UK and other countries), do not use commas at all. On May 13th, 2007 Daniel was born.

What is the format of new date ()?

By default, when you run new Date() in your terminal, it uses your browser's time zone and displays the date as a full text string, like Fri Jul 02 2021 12:44:45 GMT+0100 (British Summer Time).


1 Answers

There's nothing in ES2015 that added something like strftime no. There's an ECMAScript internationalisation spec ecma-402 which enables localised 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 US localized 8/4/2015 and 5:29:19 PM Or if you really want a 24 hour clock:

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

Then you can do a substring on the time if you want to strip out the seconds.

You can read more about date and time at MDT docs.

like image 167
Kit Sunde Avatar answered Oct 26 '22 17:10

Kit Sunde