Reputation: 143
I want to get the Month & Year from a string of Timestamp.
Attempted:
var x = "2021-09-08T17:00:00.000Z"
x.toLocaleString('en-us',{month:'short', year:'numeric'})
console.log(x)`enter code here`
Expected result
x = "September 2021"
Upvotes: 0
Views: 160
Reputation: 2288
You need to first parse it as a date object.
const x = "2021-09-08T17:00:00.000Z"
const y = new Date(x)
then you can use the date methods.
console.log(y.toLocaleString("en-us", { month: "long", year: "numeric" }));
outputs: September 2021
Upvotes: 0
Reputation: 193
You can edit your code as follows
var x = "2021-09-08T17:00:00.000Z"
var monthYear = new Date(x).toLocaleString('en-us', {
month: 'long',
year: 'numeric'
})
console.log(monthYear)
Upvotes: 2
Reputation: 25408
You can easily achieve this result using getMonth() and getFullYear() method of Date object
const x = "2021-09-08T17:00:00.000Z";
const monthNames = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const date = new Date(x);
const result = `${monthNames[date.getMonth()]} ${date.getFullYear()}`;
console.log(result);
Upvotes: 3