【发布时间】:2020-03-18 04:16:53
【问题描述】:
我正在尝试测试我的 Postgres 数据库,以确保所有内容都已正确添加,并将包含此格式 2029-01-22T16:28:32.000Z 的硬编码日期。
这是它的表格:
CREATE TABLE blogful_articles (
id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
title TEXT NOT NULL,
content TEXT,
date_published TIMESTAMP DEFAULT now() NOT NULL
);
我希望返回 2029-01-22T16:28:32.000Z,但返回 2029-01-23T00:28:32.000Z,因为 Windows 会根据时区差异自动调整它,我的测试会失败。
它应该自动调整夏令时,但这是我的解决方案:
function adjustingForTimezone(dateToAdjust) {
const offsetInMilliseconds = dateToAdjust.getTimezoneOffset() * 60000;
const theDateWithOffsetAdded =
Date.parse(dateToAdjust) - offsetInMilliseconds;
const adjustedTime = new Date(theDateWithOffsetAdded);
return adjustedTime;
}
这是我的使用方法:
app.get("/articles", (req, res, next) => {
const knexInstance = req.app.get("db");
ArticlesService.getAllArticles(knexInstance)
.then(articles => {
const os = process.platform
function adjustingForTimezone(dateToAdjust) {
const offsetInMilliseconds = dateToAdjust.getTimezoneOffset() * 60000
const theDateWithOffsetAdded = Date.parse(dateToAdjust) - offsetInMilliseconds
const adjustedTime = new Date(theDateWithOffsetAdded)
return adjustedTime
}
res.json(
articles.map(article => ({
id: article.id,
title: article.title,
style: article.style,
content: article.content,
date_published: os === "win32" ? adjustingForTimezone(article.date_published) : new Date(article.date_published)
}))
);
})
.catch(next);
});
我制作了adjustingForTimezone 应该自动调整它的函数,有什么办法可以改进它吗?在我的代码中使用它有哪些潜在的陷阱?
【问题讨论】:
标签: node.js windows postgresql timezone utc