检查 ISO 8601 字符串是否采用 UTC 格式

问题描述 投票:0回答:2

我想要一个 TypeScript 函数来检查 ISO 8601 日期时间字符串是否采用 UTC。所以输出应该是:

isUTC('2020-01-01T00:00:00Z')      // true
isUTC('2020-01-01T00:00:00+00')    // true
isUTC('2020-01-01T00:00:00+0000)   // true
isUTC('2020-01-01T00:00:00+00:00') // true
isUTC('2020-01-01T00:00:00+01)     // false
isUTC('2020-01-01T00:00:00+0100)   // false
isUTC('2020-01-01T00:00:00+01:00') // false

如果可能的话,我想避免使用正则表达式并使用现有的解析器或分解器。理想情况下会有一个分解 ISO 8601 字符串的库,以便我可以检查

Iso8601Decomposer(value).timezoneOffset === 0
。 TypeScript/JavaScript 中是否存在类似的东西?

我发现一些答案正在检查是否

value === new Date(Date.parse(value)).toISOString()
,但这不适用于上面的第2行和第3行。

javascript typescript timezone utc
2个回答
1
投票

您可以使用

luxon
库来解析 ISO 日期字符串。

然后可以在几分钟内获得 UTC 偏移量,如果这是 0,我们就处于 UTC(或 GMT)

我已将这一切包装在所需的

isUTC()
函数中。

let { DateTime } = luxon;

let inputs = [
    '2020-01-01T00:00:00Z',
    '2020-01-01T00:00:00+00',
    '2020-01-01T00:00:00+0000',
    '2020-01-01T00:00:00+00:00',
    '2020-01-01T00:00:00+01',
    '2020-01-01T00:00:00+0100',
    '2020-01-01T00:00:00+01:00'
];


function isUTC(input) {
    const dt = DateTime.fromISO(input, { setZone: true })
    return dt.offset === 0;
}

console.log('Input'.padEnd(30), 'isUTC');
for(let input of inputs) {
    console.log(input.padEnd(30), isUTC(input));
}
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

也可以使用正则表达式做到这一点:

let inputs = [
    '2020-01-01T00:00:00Z',
    '2020-01-01T00:00:00+00',
    '2020-01-01T00:00:00+0000',
    '2020-01-01T00:00:00+00:00',
    '2020-01-01T00:00:00+01',
    '2020-01-01T00:00:00+0100',
    '2020-01-01T00:00:00+01:00'
];


function isUTC(input) {
    return getUTCOffsetMinutes(input) === 0;
}

function getUTCOffsetMinutes(isoDate) {
    // The pattern will be ±[hh]:[mm], ±[hh][mm], or ±[hh], or 'Z'
    const offsetPattern = /([+-]\d{2}|Z):?(\d{2})?\s*$/;
    if (!offsetPattern.test(isoDate)) {
        throw new Error("Cannot parse UTC offset.")
    }
    const result = offsetPattern.exec(isoDate);
    return (+result[1] || 0) * 60 + (+result[2] || 0);
}

console.log('Input'.padEnd(30), 'isUTC');
for(let input of inputs) {
    console.log(input.padEnd(30), isUTC(input));
}
.as-console-wrapper { max-height: 100% !important; }


0
投票

Terry Lennox 的正则表达式

([+-]\d{2}|Z):?(\d{2})?\s*$
无效

https://www.regextester.com/112232

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.