gpt4 book ai didi

javascript - 有什么方法可以在不使用 javascript 子字符串函数或正则表达式的情况下生成此字符串日期表示形式(带时区)?

转载 作者:行者123 更新时间:2023-11-30 08:07:53 26 4
gpt4 key购买 nike

从一个新的 Date 对象开始,是否有任何方法可以仅使用 Date 对象的内置方法来生成以下字符串表示形式——也就是说,不允许使用正则表达式和/或子字符串操作? “2013-02-01T00:00:00-05:00”

最佳答案

using only the Date object's built-in methods

没有。 JavaScript 不会让您输出带有自定义时区值的 ISO 8601 字符串,.toISOSTring始终使用 Z (UTC)。

您将需要使用各种 getter 方法并自行构造字符串。基于 How do I output an ISO 8601 formatted string in JavaScript?How to convert ISOString to local ISOString in javascript? :

function customISOstring(date, offset) {
var date = new Date(date), // copy instance
h = Math.floor(Math.abs(offset)/60),
m = Math.abs(offset) % 60;
date.setMinutes(date.getMinutes() - offset); // apply custom timezone
function pad(n) { return n < 10 ? '0' + n : n }
return date.getUTCFullYear() + '-' // return custom format
+ pad(date.getUTCMonth() + 1) + '-'
+ pad(date.getUTCDate()) + 'T'
+ pad(date.getUTCHours()) + ':'
+ pad(date.getUTCMinutes()) + ':'
+ pad(date.getUTCSeconds())
+ (offset==0 ? "Z" : (offset<0 ? "+" : "-") + pad(h) + ":" + pad(m));
}

关于javascript - 有什么方法可以在不使用 javascript 子字符串函数或正则表达式的情况下生成此字符串日期表示形式(带时区)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14992051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com