javascript 如何在node.js后端获取昨天的日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31912523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get yesterday date in node.js backend?
提问by Shanthi
I am using date-formatpackage in node back end and I can get today date using
我在节点后端使用日期格式包,我可以使用今天的日期
var today = dateFormat(new Date());
In the same or some other way I want yesterday date. Still I did't get any proper method. For the time being I am calculating yesterday date manually with lot of code. Is there any other method other then writing manually ?
以我想要昨天约会的相同或其他方式。我仍然没有得到任何适当的方法。目前,我正在使用大量代码手动计算昨天的日期。除了手动编写之外还有其他方法吗?
回答by Osama Mohamed
Try this:
试试这个:
var d = new Date(); // Today!
d.setDate(d.getDate() - 1); // Yesterday!
回答by Jarrod
I would take a look at moment.js if you are interested in doing calculations with dates, there are many issues you can run into trying to do it manually or even with the built in Date objects in JavaScript/node.js such as leap years and daylight savings time issues.
如果您对使用日期进行计算感兴趣,我会看看 moment.js,尝试手动或什至使用 JavaScript/node.js 中的内置 Date 对象(例如闰年)可能会遇到许多问题和夏令时问题。
For example:
例如:
var moment = require('moment');
var yesterday = moment().subtract(1, 'days');
console.log(yesterday.format());
回答by Shubh
Try Library called node-datetime
尝试名为 node-datetime 的库
var datetime = require('node-datetime');
var dt = datetime.create();
// 7 day in the past
dt.offsetInDays(-1);
var formatted = dt.format('Y-m-d H:M:S');
console.log(formatted)
回答by venkat7668
Extract yesterday's date from today
从今天提取昨天的日期
//optimized way
var yesterday = new Date();
yesterday.setDate(yesterday.getDate()-1);
console.log(yesterday) // log yesterday's date
//in-detail way
var today = new Date();
var yesterday = new Date();
yesterday.setDate(today.getDate()-1);
console.log(yesterday) // log yesterday's date
回答by Abhilash Km
you can also change Hour,Minute,seconds and milliseconds attributes of time object like this.
您还可以像这样更改时间对象的小时、分钟、秒和毫秒属性。
var date = new Date();
date.setDate(date.getDate()-1);
date.setHours(hour);
date.setMinutes(minute);
date.setSeconds(seconds);
date.setMilliseconds(milliseconds);
回答by Russell Pekala
To get the string in a format familiar to people
以人们熟悉的格式获取字符串
// Date String returned in format yyyy-mm-dd
function getYesterdayString(){
var date = new Date();
date.setDate(date.getDate() - 1);
var day = ("0" + date.getDate()).slice(-2);
var month = ("0" + (date.getMonth() + 1)).slice(-2); // fix 0 index
return (date.getYear() + 1900) + '-' + month + '-' + day;
}
回答by Codemaker
Date class will give the current system date and current_ date - 1 will give the yesterday date.
Date 类将给出当前系统日期和 current_ date - 1 将给出昨天的日期。
Eg:
例如:
var d = new Date(); // Today!
d.setDate(d.getDate() - 1); // Yesterday!