[英]How to get correct date and month on node.js and Cloud Functions for Firebase?
[英]How to get the first date of the current month in Node.js?
我正在尝试使用 Node.js 获取当月的第一个和最后一个日期。
以下代码在浏览器(Chrome)中完美运行:
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
console.log(firstDay);
console.log(lastDay);
但它在 Node.js 中显示出不同的结果。 我该如何解决?
在接受的答案中更改本机Date
对象是不好的做法; 不要这样做( https://stackoverflow.com/a/8859896/3929494 )
您应该使用 moment.js 为您提供一个一致的环境,用于在 node.js 和所有浏览器之间处理 JavaScript 中的日期 - 将其视为一个抽象层。 http://momentjs.com/ - 它很容易使用。
一个非常相似的例子在这里: https : //stackoverflow.com/a/26131085/3929494
浏览器输出显示当前时区的日期,node.js 显示日期 GMT / Zulu 时区。
(编辑:添加了代码)。 像这样的东西
var offset = (new Date().getTimezoneOffset() / 60) * -1;
var d = new Date();
var tmpDate = new Date(d.getTime()+offset);
var y = tmpDate.getFullYear();
var m = tmpDate.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
console.log(tmpDate.toString());
console.log(firstDay.toString());
console.log(lastDay.toString());
创建一个新文件dates.js并添加以下代码。 要执行此代码,请从终端运行命令节点dates.js 。 您可以使用此函数获取给定月份的第一天和最后一天的日期。 我在节点 12上测试了这个
const getDays = () => {
const date = new Date();
const year = date.getFullYear();
let month = date.getMonth() + 1;
let f = new Date(year, month, 1).getDate();
let l = new Date(year, month, 0).getDate();
f = f < 10 ? '0'+f : f;
l = l < 10 ? '0'+l : l;
month = month < 10 ? '0'+month : month;
const firstDay = new Date(`${year}-${month}-${f}`);
const lastDay = new Date(`${year}-${month}-${l}`);
console.log({
"firstDay": firstDay,
"lastDay": lastDay
});
};
getDays();
看代码
<html>
<head>
<title>Please Rate if it helps</title>
<script>
Date.prototype.getMonthStartEnd = function (start) {
var StartDate = new Date(this.getFullYear(), this.getMonth(), 1);
var EndDate = new Date(this.getFullYear(), this.getMonth() + 1, 0);
return [StartDate, EndDate];
}
window.onload = function () {
document.write(new Date().getMonthStartEnd());
}
</script>
</head>
<body>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.