[英]How to subtract days from a plain Date?
有没有一种简单的方法可以将 olain JavaScript Date
(例如今天)返回 X 天?
因此,例如,如果我想计算今天前 5 天的日期。
尝试这样的事情:
var d = new Date();
d.setDate(d.getDate()-5);
请注意,这会修改日期对象并返回更新日期的时间值。
var d = new Date(); document.write('Today is: ' + d.toLocaleString()); d.setDate(d.getDate() - 5); document.write('<br>5 days ago was: ' + d.toLocaleString());
var dateOffset = (24*60*60*1000) * 5; //5 days
var myDate = new Date();
myDate.setTime(myDate.getTime() - dateOffset);
如果您在整个 Web 应用程序中执行大量令人头疼的日期操作, DateJS将使您的生活更轻松:
它是这样的:
var d = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);
我注意到 getDays+ X 在日/月范围内不起作用。 只要您的日期不早于 1970 年,就可以使用 getTime。
var todayDate = new Date(), weekDate = new Date();
weekDate.setTime(todayDate.getTime()-(7*24*3600000));
获取moment.js。 所有酷孩子都使用它。 它有更多的格式选项等。哪里
var n = 5;
var dateMnsFive = moment(<your date>).subtract(n , 'day');
可选的! 转换为 JS 日期 obj 以进行 Angular 绑定。
var date = new Date(dateMnsFive.toISOString());
可选的! 格式
var date = dateMnsFive.format("YYYY-MM-DD");
我发现 getDate()/setDate() 方法的一个问题是它太容易将所有内容都变成毫秒,而且语法有时对我来说很难理解。
相反,我喜欢解决 1 天 = 86,400,000 毫秒的事实。
因此,对于您的特定问题:
today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))
奇迹般有效。
我一直使用这种方法进行滚动 30/60/365 天计算。
您可以轻松地推断出这一点,以创建月、年等的时间单位。
我为 Date 制作了这个原型,以便我可以传递负值来减去天数,传递正值来增加天数。
if(!Date.prototype.adjustDate){
Date.prototype.adjustDate = function(days){
var date;
days = days || 0;
if(days === 0){
date = new Date( this.getTime() );
} else if(days > 0) {
date = new Date( this.getTime() );
date.setDate(date.getDate() + days);
} else {
date = new Date(
this.getFullYear(),
this.getMonth(),
this.getDate() - Math.abs(days),
this.getHours(),
this.getMinutes(),
this.getSeconds(),
this.getMilliseconds()
);
}
this.setTime(date.getTime());
return this;
};
}
所以,要使用它,我可以简单地写:
var date_subtract = new Date().adjustDate(-4),
date_add = new Date().adjustDate(4);
一些现有的解决方案很接近,但并不完全是我想要的。 此函数适用于正值或负值并处理边界情况。
function addDays(date, days) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() + days,
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
我喜欢以毫秒为单位进行数学计算。 所以使用Date.now()
var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds
如果你喜欢它的格式
new Date(newDate).toString(); // or .toUTCString or .toISOString ...
注意: Date.now()
在旧浏览器中不起作用(例如我认为 IE8)。 在这里填充。
@socketpair 指出了我的草率。 正如他/她所说的“一年中的某一天有 23 小时,由于时区规则,大约有 25 小时”。
为了扩展这一点,如果您想在夏令时更改的时区中计算 5 天前的 LOCAL 天,那么上面的答案将有夏令时不准确
Date.now()
为您提供当前的 LOCAL 现在时间,或.toString()
返回本地日期,因此与 UTC 中的Date.now()
基准日期不兼容。但是,如果您在 UTC 中进行数学运算,则它有效,例如
A. 您想要 5 天前从现在 (UTC) 开始的 UTC 日期
var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds UTC
new Date(newDate).toUTCString(); // or .toISOString(), BUT NOT toString
B. 您从“现在”以外的 UTC 基准日期开始,使用Date.UTC()
newDate = new Date(Date.UTC(2015, 3, 1)).getTime() + -5*24*3600000;
new Date(newDate).toUTCString(); // or .toISOString BUT NOT toString
将您的日期分成几部分,然后返回一个带有调整值的新日期
function DateAdd(date, type, amount){
var y = date.getFullYear(),
m = date.getMonth(),
d = date.getDate();
if(type === 'y'){
y += amount;
};
if(type === 'm'){
m += amount;
};
if(type === 'd'){
d += amount;
};
return new Date(y, m, d);
}
请记住,月份是从零开始的,但天数不是。 即 new Date(2009, 1, 1) == 2009 年 2 月 1 日,new Date(2009, 1, 0) == 2009 年 1 月 31 日;
在不使用第二个变量的情况下,您可以将 7 for 替换为您的返回 x 天:
let d=new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000))
function addDays (date, daysToAdd) { var _24HoursInMilliseconds = 86400000; return new Date(date.getTime() + daysToAdd * _24HoursInMilliseconds); }; var now = new Date(); var yesterday = addDays(now, - 1); var tomorrow = addDays(now, 1);
我创建了一个用于日期操作的函数。 您可以添加或减去任意数量的天数、小时数、分钟数。
function dateManipulation(date, days, hrs, mins, operator) {
date = new Date(date);
if (operator == "-") {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() - durationInMs);
} else {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() + durationInMs);
}
return newDate;
}
现在,通过传递参数来调用这个函数。 例如,这里有一个函数调用,用于获取距今天 3 天前的日期。
var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");
使用MomentJS 。
function getXDaysBeforeDate(referenceDate, x) { return moment(referenceDate).subtract(x , 'day').format('MMMM Do YYYY, h:mm:ss a'); } var yourDate = new Date(); // let's say today var valueOfX = 7; // let's say 7 days before console.log(getXDaysBeforeDate(yourDate, valueOfX));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
请参阅以下代码,从当前日期中减去天数。 此外,根据减去日期设置月份。
var today = new Date();
var substract_no_of_days = 25;
today.setTime(today.getTime() - substract_no_of_days* 24 * 60 * 60 * 1000);
var substracted_date = (today.getMonth()+1) + "/" +today.getDate() + "/" + today.getFullYear();
alert(substracted_date);
有些人建议使用 moment.js 在 js 中处理日期时使您的生活更轻松。 自这些答案以来已经过去了一段时间,值得注意的是,moment.js 的作者现在不鼓励使用它。 主要是由于它的大小和缺乏摇树支持。
如果您想走图书馆路线,请使用Luxon 之类的替代品。 它明显更小(因为它巧妙地使用了Intl 对象并支持摇树)并且与 moment.js 一样通用。
要从今天起回到 Luxon 的 5 天,您将执行以下操作:
import { DateTime } from 'luxon'
DateTime.now().minus({ days: 5 });
最重要的答案导致了我的代码中的一个错误,即在当月的第一天它会设置当月的未来日期。 这是我所做的,
curDate = new Date(); // Took current date as an example
prvDate = new Date(0); // Date set to epoch 0
prvDate.setUTCMilliseconds((curDate - (5 * 24 * 60 * 60 * 1000))); //Set epoch time
如果您希望将所有内容都放在一行上。
从今天起 5 天
//past
var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5));
//future
var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5));
从特定日期起 5 天
var pastDate = new Date('2019-12-12T00:00:00');
//past
var fiveDaysAgo = new Date(new Date().setDate(pastDate.getDate() - 5));
//future
var fiveDaysInTheFuture = new Date(new Date().setDate(pastDate.getDate() + 5));
我写了一个你可以使用的函数。
function AddOrSubractDays(startingDate, number, add) { if (add) { return new Date(new Date().setDate(startingDate.getDate() + number)); } else { return new Date(new Date().setDate(startingDate.getDate() - number)); } } console.log('Today : ' + new Date()); console.log('Future : ' + AddOrSubractDays(new Date(), 5, true)); console.log('Past : ' + AddOrSubractDays(new Date(), 5, false));
管理日期的一种简单方法是使用Moment.js
您可以使用add
。 例子
var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days'); //Add 5 days to start date
alert(new_date);
对我来说,所有组合都可以与下面的代码片段一起使用,该片段用于 Angular-2 实现,如果您需要添加天数,请传递正数 numberofDays,如果您需要减去传递负数天数
function addSubstractDays(date: Date, numberofDays: number): Date {
let d = new Date(date);
return new Date(
d.getFullYear(),
d.getMonth(),
(d.getDate() + numberofDays)
);
}
我喜欢以下内容,因为它是一行。 DST 更改并不完美,但通常足以满足我的需求。
var fiveDaysAgo = new Date(new Date() - (1000*60*60*24*5));
我在 date.js 中获得了很好的里程:
d = new Date();
d.add(-10).days(); // subtract 10 days
好的!
网站包括这个美丽:
Datejs 不只是解析字符串,它还将它们一分为二
如果您想减去天数并将日期格式化为人类可读的格式,您应该考虑创建一个自定义DateHelper
对象,如下所示:
var DateHelper = { addDays : function(aDate, numberOfDays) { aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays return aDate; // Return the date }, format : function format(date) { return [ ("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes ("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes date.getFullYear() // Get full year ].join('/'); // Glue the pieces together } } // With this helper, you can now just use one line of readable code to : // --------------------------------------------------------------------- // 1. Get the current date // 2. Subtract 5 days // 3. Format it // 4. Output it // --------------------------------------------------------------------- document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), -5));
(另见这个小提琴)
了解如何使用momentjs查找今天之前的5天。
moment(Date.now() - 5 * 24 * 3600 * 1000).format('YYYY-MM-DD') // 2019-01-03
我在玩耍,发现一个简单的解决方案:
使用.setDate(+daysCount|-daysCount)
; 符号=|-
是必须的;
let today = new Date(); today.setDate(-100); console.log('date100DaysAgo', today); today = new Date(); today.setDate(+100); console.log('date100DaysAhead', today);
要计算具有比整日更精确差异的相对时间戳,您可以使用 Date.getTime() 和 Date.setTime() 来处理表示自某个时期(即 1970 年 1 月 1 日)以来的毫秒数的整数。对于例如,如果您想知道现在是 17 小时后:
const msSinceEpoch = (new Date()).getTime(); const fortyEightHoursLater = new Date(msSinceEpoch + 48 * 60 * 60 * 1000).toLocaleString(); const fortyEightHoursEarlier = new Date(msSinceEpoch - 48 * 60 * 60 * 1000).toLocaleString(); const fiveDaysAgo = new Date(msSinceEpoch - 120 * 60 * 60 * 1000).toLocaleString(); console.log({msSinceEpoch, fortyEightHoursLater, fortyEightHoursEarlier, fiveDaysAgo})
function daysSinceGivenDate (date) {
const dateInSeconds = Math.floor((new Date().valueOf() - date.valueOf()) / 1000);
const oneDayInSeconds = 86400;
return Math.floor(dateInSeconds / oneDayInSeconds); // casted to int
};
console.log(daysSinceGivenDate(new Date())); // 0
console.log(daysSinceGivenDate(new Date("January 1, 2022 03:24:00"))); // relative...
const EditDay = (date: Date, num: number): Date => {
return new Date(date.getTime() + num * 24 * 60 * 60 * 1000)
}
设置日期时,日期转换为毫秒,因此需要将其转换回日期:
这种方法还考虑了新年变化等。
function addDays( date, days ) {
var dateInMs = date.setDate(date.getDate() - days);
return new Date(dateInMs);
}
var date_from = new Date();
var date_to = addDays( new Date(), parseInt(days) );
您可以使用 Javascript。
var CurrDate = new Date(); // Current Date
var numberOfDays = 5;
var days = CurrDate.setDate(CurrDate.getDate() + numberOfDays);
alert(days); // It will print 5 days before today
对于 PHP,
$date = date('Y-m-d', strtotime("-5 days")); // it shows 5 days before today.
echo $date;
希望它会帮助你。
我转换成毫秒并扣除其他月份和年份的天数不会改变和合乎逻辑
var numberOfDays = 10;//number of days need to deducted or added
var date = "01-01-2018"// date need to change
var dt = new Date(parseInt(date.substring(6), 10), // Year
parseInt(date.substring(3,5), 10) - 1, // Month (0-11)
parseInt(date.substring(0,2), 10));
var new_dt = dt.setMilliseconds(dt.getMilliseconds() - numberOfDays*24*60*60*1000);
new_dt = new Date(new_dt);
var changed_date = new_dt.getDate()+"-"+(new_dt.getMonth()+1)+"-"+new_dt.getFullYear();
希望有帮助
var date = new Date(); var day = date.getDate(); var mnth = date.getMonth() + 1; var fDate = day + '/' + mnth + '/' + date.getFullYear(); document.write('Today is: ' + fDate); var subDate = date.setDate(date.getDate() - 1); var todate = new Date(subDate); var today = todate.getDate(); var tomnth = todate.getMonth() + 1; var endDate = today + '/' + tomnth + '/' + todate.getFullYear(); document.write('<br>1 days ago was: ' + endDate );
使用现代 JavaScript 函数语法
const getDaysPastDate = (daysBefore, date = new Date) => new Date(date - (1000 * 60 * 60 * 24 * daysBefore)); console.log(getDaysPastDate(1)); // yesterday
尝试这样的事情
dateLimit = (curDate, limit) => {
offset = curDate.getDate() + limit
return new Date( curDate.setDate( offset) )
}
currDate可以是任何日期
限制可能是天数的差异(未来为正,过去为负)
是否有一种简单的方法来获取无效的JavaScript Date
(例如今天)并返回X天?
因此,例如,如果我想计算今天之前5天的日期。
var daysToSubtract = 3;
$.datepicker.formatDate('yy/mm/dd', new Date() - daysToSubtract) ;
var d = new Date(); document.write('Today is: ' + d.toLocaleString()); d.setDate(d.getDate() - 31); document.write('<br>5 days ago was: ' + d.toLocaleString());
var my date = new Date().toISOString().substring(0, 10);
它只能给你像 2014-06-20 这样的日期。 希望会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.