How do I format a date using javascript: for example, change "2018-10-25T15:00:00.000Z" to Sat, "10/25" ?
Please and thank you
How do I format a date using javascript: for example, change "2018-10-25T15:00:00.000Z" to Sat, "10/25" ?
Please and thank you
Using toLocaleString you could do:
console.log(
(new Date())
.toLocaleString(
window.navigator.language,
{month:"2-digit",day:"2-digit",weekday: 'short'}
)
);
console.log(
(new Date())
.toLocaleString(
"zh-CN",
{month:"2-digit",day:"2-digit",weekday: 'short'}
)
)
Using toLacaleString
will get you a string based on locale and as Rob pointed out in the comment; this may differ even in different browsers.
If you want to show the user a local string then this is good but if you want to automatically process that string it's better to use something else like milliseconds after epoch UTC.
The format you provided would suggest user only because it's unfit for automatic processing (there is no timezone or year).
Maybe you are trying to combine formatted string to show the user with something you need to process later. In that case I would advice you to use tuple (array) that contains both ms after epoch and user formatted string.
Anyway, if you want to mix up formatted for human consumption with automation then you can do the following:
var d = new Date();
["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][d.getDay()]+", "+
new String("0"+(d.getMonth()+1)).slice(-2) + "/" +
new String("0"+d.getDate()).slice(-2)
Moment.js library could probably save you a lot of time with this tedious task:
moment(new Date('2018-10-25T15:00:00.000Z')).format("dddd, MM/D")
output:
"Thursday, 10/25"
You can mess around with it by opening the JS console on their docs page, as moment is loaded on it.
Edit- as noted in comments, if this is the only task you are using it for, probably best not to use a lib and do it in plain JS!