1

我的日期是字符串,像这样2020 年 7 月 13 日 如何使用用户定义函数javascript将其转换为 cosmos db 日期格式“2020-10-07T00:00:00.000Z”

4

1 回答 1

0

您可以使用 String.split() 将日期拆分为其组成部分,然后使用 Date.UTC 转换为 unix 时间。注意:我假设您的日期 2020 年 7 月 13 日是 UTC。如果是当地时间,我们将使用 new Date(year, month, day) 代替。

// Use this if your date string refers to UTC time
function parseUTCTimestamp(s) {
    const monthIndexes = { 
        jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
        jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 
    };
    const [day, month, year] = s.toLowerCase().split('-');
    return new Date(Date.UTC(year, monthIndexes[month], day)).toISOString();
}

console.log("UTC:", parseUTCTimestamp("13-Jul-2020"));
console.log("UTC:", parseUTCTimestamp("17-aug-2020"));

// Use this if your date string refers to local time
function parseLocalTimestamp(s) {
    const monthIndexes = { 
        jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
        jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 
    };
    const [day, month, year] = s.toLowerCase().split('-');
    return new Date(year, monthIndexes[month], day).toISOString();
}

console.log("Local:", parseLocalTimestamp("13-Jul-2020"));
console.log("Local:", parseLocalTimestamp("17-aug-2020"));

于 2020-08-17T07:50:54.793 回答