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?
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With