如何解决在Moment.js中获取本地日期时间JSON
我的代码如下:
var startTime = moment("2020-09-08 16:00:00").toDate();
console.log(startTime)
const data = {start: startTime}
console.log(JSON.stringify(data)
当我跑步时,结果为:
Tue Sep 08 2020 16:00:00 GMT+0700 (Indochina Time)
{"start":"2020-09-08T09:00:00.000Z"}
我不知道为什么结果显示不同的时区? 有人帮我解释和解决吗?
谢谢!
解决方法
默认情况下,JSON.stringify会将日期转换为时间戳,就像在该日期上调用了 toISOString 一样。
如果您希望使用其他格式的日期,则可以使用replacer function来测试与JSON.stringify产生的格式相同的时间戳(即YYYY-MM-DDTHH:mm) :ss.sssZ),而是将其字符串化为其他格式,例如使用Date.prototype.toString。
请注意,您必须测试格式化的字符串,因为该值在传递给替换器函数之前将被字符串化。
// Test if value is a string in the same format as that produced
// by toISOString
function isTimestamp(value) {
return /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(value);
}
// Replace timestamps in toISOString format with
// timestamps in toString format
function replacer (key,value) {
console.log(Object.prototype.toString.call(this[key]));
if (isTimestamp(value)) {
return this[key].toString();
} else {
return value;
}
}
// Sample date
let startTime = new Date(2020,8,16);
// Sample object
let data = {start: startTime};
// Stringify date using toString
console.log(JSON.stringify(data,replacer))
或者,您可以在替换程序中测试this[key]
的值,而不使用 isTimestamp 函数,例如:
if (Object.prototype.toString.call(this[key]) == '[object Date]') {
// return custom format
}
使用moment.js,您可以这样做:
// Replace timestamps in toISOString format with
// timestamps in some other format
function replacer(key,value) {
// Strict parse of value
let d = moment(value,'YYYY-MM-DDTHH:mm:ss.sssZ',true);
// If it's a valid Date
if (d.isValid()) {
// Return whatever format you like
return moment(this[key]).format('YYYY-MM-DD HH:mm ZZ');
} else {
// Otherwise just return the default value
return value;
}
}
// Sample date
let startTime = new Date(2020,replacer))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。