我有一个API,其日期格式类似于01/04/2020 00:17:26
,我们在下面使用JavaScript代码:
function getLocalTime(timestamp){
try {
let localTime = new Date(timestamp.replace('at ','') + ' GMT+530');
return localTime;
} catch(e){
return timestamp;
}
}
vat date = getLocalTime('01/04/2020 00:17:26');
console.log(date);
上面的代码返回Sat Jan 04 2020 00:17:26 GMT+0530 (India Standard Time)
,但预期结果将类似于Wed Apr 01 2020 00:17:26 GMT+0530 (India Standard Time)
请帮助我们。
问题是您使用的日期格式错误。
您的格式:DD/MM/YYYY
预期格式:MM/DD/YYYY
仍然,如果您期望(来自用户)的输入格式是DD/MM/YYYY
(例如01/04/2020 00:17:26
,那么您可以像这样使用正则表达式来提取日期信息] >>
function getLocalTime(timestamp){
try {
const datePart = timestamp.match(/^(\d{2})\/(\d{2})\/(\d{4})/);
const day = datePart[1];
// month goes from 0 to 11
const month = datePart[2] - 1;
const year = datePart[3];
const localTime = new Date(timestamp.replace('at ','') + ' GMT+0530');
localTime.setFullYear(year);
localTime.setMonth(month);
localTime.setDate(day);
return localTime;
} catch(e){
return timestamp;
}
}
const date = getLocalTime('01/04/2020 00:17:26');
console.log(date);