For a specific application, I need to convert my date format from
Fri Mar 26 2021 16:00:01 GMT+0400 (Gulf Standard Time)
to
January 01, 2023 00:00:00 GMT+03:00
How can I do that?
For a specific application, I need to convert my date format from
Fri Mar 26 2021 16:00:01 GMT+0400 (Gulf Standard Time)
to
January 01, 2023 00:00:00 GMT+03:00
How can I do that?
This is how I solved the format problem:
//1. Get closing time from event
time = new Date(item.returnValues['closingTime'] * 1000);
//2. Formatting the date for the date counter input
const options = { year: 'numeric', month: 'long', day: 'numeric' };
firstPart= time.toLocaleDateString('en-US', options);
//3. Get original GMT time from the var time
secondPart = time.toString().slice(15, 24);
secondPart = secondPart.concat(" GMT+04:00 ");
//4. concat the two strings into the desired form
ct = firstPart.concat(secondPart);
Based on mozila's documents, when the time wants to display as a string, The first three letters always stand for weekday name and they will be separate from the other data with a single space, so we can omit 4 first characters (3 first letters + followed space) from the final string with a function like this :
let sampleDate = Date();
function sliceDayFromTime(dateTime) {
return dateTime.slice(4);
}
console.log(sliceDayFromTime(sampleDate));
In order to use more advanced formatting, you can use Intl.DateTimeFormat which is an object that enables language-sensitive date and time formatting.
For the specific example that you mentioned above, I believe that the code below is useful
var sampleDate = new Date();
var formatter = new Intl.DateTimeFormat('en-us', {
month: 'long',
year: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
timeZoneName: 'short'
});
function minimalFormatDate(date) {
return formatter.format(date);
}
function advancedFromatDate(date) {
return formatter.formatToParts(date).map(({type, value}, index) => {
if (type === 'literal' && index === 5) {
return ' '
}
return value;
}).join('');
}
console.log('minimal formating example: ', minimalFormatDate(sampleDate));
console.log('advanced formating example: ', advancedFromatDate(sampleDate));