1 回答

TA貢獻1770條經驗 獲得超3個贊
問題是您使用的日期格式錯誤。
你的格式: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);
更新
@RobG 提出了一個很棒的解決方案(見下面的評論)。
function getLocalTime(timestamp) {
try {
const matches = timestamp.split(/\D+/); // or use timestamp.match(/\d+/g)
return new Date(Date.UTC(matches[2], matches[1]-1, matches[0], matches[3]-5, matches[4]-30, matches[5]));
} catch(e){
return timestamp;
}
}
const date = getLocalTime('01/04/2020 00:17:26');
console.log(date);
添加回答
舉報