如何从时间戳字符串获得月-年?



我想获得月份&

:

var x =  "2021-09-08T17:00:00.000Z"

x.toLocaleString('en-us',{month:'short', year:'numeric'})

console.log(x)`enter code here`

预期结果

x = "September 2021"

您可以使用Date对象的getMonth()和getFullYear()方法轻松实现此结果

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);

您可以这样编辑您的代码

var x = "2021-09-08T17:00:00.000Z"
var monthYear = new Date(x).toLocaleString('en-us', {
month: 'long',
year: 'numeric'
})
console.log(monthYear)

首先需要将其解析为日期对象。


const x =  "2021-09-08T17:00:00.000Z"
const y = new Date(x)

则可以使用日期方法。


console.log(y.toLocaleString("en-us", { month: "long", year: "numeric" }));
输出:September 2021

最新更新