从 Intl.DateTimeFormat 生成的日期中删除逗号 (,)
Remove Comma (,) from Date which is generated from Intl.DateTimeFormat
使用 Intl.DateTimeFormat 以类似于“2021 年 1 月 15 日,2:30:11 下午”的格式获取时间。
function formatDate(date) {
const someDate = new Intl.DateTimeFormat('en-IN', {
dateStyle: 'medium',
timeStyle: 'medium',
}).format(date);
return someDate;
}
console.log(formatDate(1610701211000))
我正在尝试删除“,”以获取格式类似于“15-Jan-2021 2:30:11 pm”的日期。根据 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts,我们将能够使用 formatToParts(date) 单独获取信息并连接必要的字段。但是,尝试在下面的代码片段中使用 formatToParts(date) 会引发“formatToParts 不是函数”错误。
如何删除上面代码段中返回的“,”?
function formatDate(date) {
const someDate = new Intl.DateTimeFormat('en-IN', {
dateStyle: 'medium',
timeStyle: 'medium',
}).format(date);
// error thrown: formatToParts is not a function
console.log(someDate.formatToParts(date));
return someDate;
}
console.log(formatDate(1610701211000))
您从错误的对象调用了 formatToParts
您可能只想使用日期替换
两种方式都有
function formatDate(ms) {
const date = new Date(ms)
const formatter = new Intl.DateTimeFormat('en-IN', {
dateStyle: 'medium',
timeStyle: 'medium',
})
const someDate = formatter.format(date)
const parts = formatter.formatToParts(date)
// the hard way same as just doing a replace:
const fromParts = Object.values(parts)
.map(({value}) => value === ", " ? " " : value)
.join("")
console.log(fromParts);
return someDate.replace(/, /g, " "); // a simple replace removes the comma
}
console.log(formatDate(1610701211000))
使用 Intl.DateTimeFormat 以类似于“2021 年 1 月 15 日,2:30:11 下午”的格式获取时间。
function formatDate(date) {
const someDate = new Intl.DateTimeFormat('en-IN', {
dateStyle: 'medium',
timeStyle: 'medium',
}).format(date);
return someDate;
}
console.log(formatDate(1610701211000))
我正在尝试删除“,”以获取格式类似于“15-Jan-2021 2:30:11 pm”的日期。根据 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts,我们将能够使用 formatToParts(date) 单独获取信息并连接必要的字段。但是,尝试在下面的代码片段中使用 formatToParts(date) 会引发“formatToParts 不是函数”错误。
如何删除上面代码段中返回的“,”?
function formatDate(date) {
const someDate = new Intl.DateTimeFormat('en-IN', {
dateStyle: 'medium',
timeStyle: 'medium',
}).format(date);
// error thrown: formatToParts is not a function
console.log(someDate.formatToParts(date));
return someDate;
}
console.log(formatDate(1610701211000))
您从错误的对象调用了 formatToParts
您可能只想使用日期替换
两种方式都有
function formatDate(ms) {
const date = new Date(ms)
const formatter = new Intl.DateTimeFormat('en-IN', {
dateStyle: 'medium',
timeStyle: 'medium',
})
const someDate = formatter.format(date)
const parts = formatter.formatToParts(date)
// the hard way same as just doing a replace:
const fromParts = Object.values(parts)
.map(({value}) => value === ", " ? " " : value)
.join("")
console.log(fromParts);
return someDate.replace(/, /g, " "); // a simple replace removes the comma
}
console.log(formatDate(1610701211000))