I'm trying to write a script to subtract 5 days from a defined date but seems not working, here's my code:
var End_Day = sheet.getRange(i + 2, 20).getValue();
Logger.log(End_Day);
var End_day_2 = new Date();
End_day_2.setDate(End_Day.getDate()-5);
Logger.log(End_day_2);
and the result is not just - 5 days:
11:18:47 AM Info Sat Jun 04 00:00:00 GMT+08:00 2022
11:18:47 AM Info Fri Apr 29 11:18:47 GMT+08:00 2022
I am quite confused why the date move from Jun to Apr.
Thanks for having a look
Try:
var End_Day = sheet.getRange(i + 2, 20).getValue();
var End_day_2 = new Date(End_Day.getTime() - (5 * (1000 * 60 * 60 * 24)))
Logger.log(End_Day);
Logger.log(End_day_2);
Function:
const endDay = sheet.getRange(i + 2, 20).getValue()
const endDay2 = DateFromDaysAgo(endDay, 5)
...
function DateFromDaysAgo(startDate, number) {
if (typeof startDate === `string`) { startDate = new Date(startDate) }
return new Date(startDate.getTime() - (number * (1000 * 60 * 60 * 24)))
}
You should learn more about Date.prototype.setDate().It only changes the day of the month of a given Date instance.
As the code you posted, the day of the month of End_Day is 4, End_day_2.setDate(4 - 5) equals to End_day_2.setDate(-1) and the month of End_day_2 is April according to the console result, because there're 30 days in April, setDate(-1) means setDate(29), so you got Apr 29 at the end. That's how it goes.
One right way to do is substracting 5 days worth of milliseconds.
function addDays(date, days){
const DAY_IN_MILLISECONDS = 24 * 60 * 60000;
return new Date(date.getTime() + days * DAY_IN_MILLISECONDS);
}
console.log(addDays(new Date(), -5).toString()); // 5 days ago
I am quite confused why the date move from Jun to Apr.
It's because you're setting date on today(End_day_2) and not on your predefined date(End_day).
Change
End_day_2.setDate(End_Day.getDate()-5);
to
End_Day.setDate(End_Day.getDate()-5);
console.info(End_Day);
If what's coming from the sheet is a string, you will have to convert the date string into a date object.
The other thing is you have to work in milliseconds as #vanowm says:
606024*5 = 432000 * 1000 = 432000000
so skipping the sheet entirely:
x = new Date
> Fri May 27 2022 11:24:01 GMT-0400 (Eastern Daylight Time)
y = new Date(x - 432000000)
> Sun May 22 2022 11:24:01 GMT-0400 (Eastern Daylight Time)
This will do the trick. Works with any date and can subtract any number of days
const subtractDays = (fromDate, numDays) => {
if (!(fromDate instanceof Date)) throw 'The first argument must be a date';
return new Date(new Date().setDate(fromDate.getDate() - +numDays));
};
Weekago
function weekago() {
let dt = new Date();
dt.setDate(dt.getDate()-7);
Logger.log(dt);
return dt;
}
Five days ago
function fiveago() {
let dt = new Date();
dt.setDate(dt.getDate()-5)
Logger.log(dt);
return dt;
}
Five days from a date in a spreadsheet cell
function fivefromadateinspreadsheet() {
const v = SpreadsheetApp.getActiveSheet().getRange("A1").getValue();
let dt = new Date(v);
dt.setDate(dt.getDate()-5);//Note that does not return a date it return the numbrer of milliseconds
Logger.log(dt);
return dt;
}
You can subtract 5 days from a defined date in Google App Script by using the Utilities.formatDate() method. Here's an example:
function subtractDays() {
var date = new Date();
var subtractDays = 5;
// Subtract 5 days from the current date
date.setDate(date.getDate() - subtractDays);
// Format the new date
var newDate = Utilities.formatDate(date, "UTC", "yyyy-MM-dd");
Logger.log(newDate);
}
In this example, we first create a Date object to represent the current date. Then, we subtract 5 days from the current date by using the setDate() method. Finally, we format the new date using the Utilities.formatDate() method and log it to the console using the Logger.log() method.
You can modify the subtractDays variable to subtract a different number of days from the date, or you can use a different date object to start with.
I am given a unix timestamp like this: 1655402413 and am needing to find find the midnight of the Monday (in UTC/GMT format) of the same week, regardless of what day it is or what time zone. I then need to represent that Monday as a unix timestamp and return it. The function I have is as follows:
function findMonday(unixTimeStamp) {
let startDate = new Date(unixTimeStamp);
let startDay = startDate.getDay();
let diff = startDate.getDate() - startDay + (startDay === 0 ? -6 : 1);
let monday = new Date(startDate.setDate(diff));
monday.setHours(0, 0, 0, 0);
monday = new Date(monday).valueOf();
return monday;
}
That function almost works, but there are two problems, both related to the fact that the Date seems to always work with the user's current timezone:
If given a timestamp that evaluates to midnight on a Monday in UTC/GMT format, depending on the time zone of the user, it returns the Monday of the previous week (because startDate evaluates to the Sunday before the Monday), which is not good.
The monday that is returned is in local time, not UTC/GMT time.
This is driving me absolutely insane. Working with dates in JavaScript is a nightmare, and I would appreciate any direction you can give me.
Multiply the unix timestamp by 1000, and use the UTC methods like getUTCDate instead of getDate, setUTCHours instead of setHours etc..
Of course to return as unix time, just divide by 1000.
eg.
function findMonday(unixTimeStamp) {
let startDate = new Date(unixTimeStamp * 1000);
let startDay = startDate.getUTCDay();
let diff = startDate.getUTCDate() - startDay + (startDay === 0 ? -6 : 1);
let monday = new Date(startDate.setUTCDate(diff));
monday.setUTCHours(0, 0, 0, 0);
monday = new Date(monday).valueOf();
return monday;
}
const monday = findMonday(1655402413);
const unixMonday = Math.trunc(monday / 1000);
console.log('The Date: ' + new Date(monday).toISOString());
console.log('Unix time: ' + unixMonday);
As for Keith's answer but a little more concise. It returns seconds, not milliseconds. ;-)
// Given UNIX timestamp, return similar timestamp for
// previous UTC Monday at 00:00:00
let getLastUTCMonday = ts => {
let d = new Date(ts * 1e3);
d.setUTCDate(d.getUTCDate() - (d.getUTCDay() || 7) + 1);
return d.setUTCHours(0,0,0,0) / 1e3 | 0;
};
let ts = 1655402413;
let tsPriorMonday = getLastUTCMonday(ts)
console.log(
`Start date : ${new Date(ts*1e3).toUTCString()}\n` +
`Prior Monday: ${new Date(tsPriorMonday * 1e3).toUTCString()}`
);
In ECMA-262, offsets from the epoch (in milliseconds) are called "time values". A timestamp is anything that represents a time or date, so a time value is a timestamp. ;-)
Given that ECMAScript UTC days are always exactly 8.64e7 milliseconds long, you can work out the previous UTC Monday from today by some simple arithmetic.
The ECMAScript epoch was Thursday, 1 Jan 1970 00:00:00, so you can:
Subtract 4 UTC days worth of milliseconds (34.56e7) from the date to align with Monday instead of Thursday
Get the remainder of dividing that value by the number of milliseconds in 7 UTC days (7 * 8.64e7 or 60.48e7)
Subtract the remainder from the current date, which will return the previous Monday and also remove the time component
The above algorithm only works for dates after the epoch. Dates before then have time values are negative so add 3 days before getting the remainder, then subtract the remainder + 7 days (i.e. date - remainder - 7 days).
The following just does the post–epoch calculation:
let getPreviousUTCMonday = date => {
let weekRem = (date - 34.56e7) % 60.48e7;
return date - weekRem;
}
let d = new Date();
for (let i=0; i<12; i++) {
console.log(`${d.toUTCString()}\n` +
`${new Date(getPreviousUTCMonday(d)).toUTCString()}`);
d.setDate(d.getDate() + 1);
}
I am trying to get the date range of the past Wednesday to past Tuesday(7 days) from today's date.
Say the current date is 2022-05-01(May 1st), I am expecting the result to be the past Tuesday(end date) to Past Wednesday (start date = Past Tuesday -7 days)
i.e 20 April 2022 to 26 April 2022
function getStartAndEndDates () {
var now = new Date('2022-05-01'); //May 1st 2022
var day = now.getDay();
var diff = (day <= 2) ? (7 - 2 + day ) : (day - 2);
var PastTuesday = new Date();
var PastWednesday = new Date(PastTuesday.setDate(now.getDate() - diff));
console.log('End date is', PastTuesday.toISOString());
PastWednesday.setDate(PastTuesday.getDate() - 6);
console.log('Start Date is',PastWednesday.toISOString());
return[PastWednesday,PastTuesday];
}
Output obtained is:
End date is 2022-03-27T19:25:35.726Z //here month is set to March
Start Date is 2022-03-21T19:25:35.726Z
Expected Result is
End date is 2022-04-26T19:25:35.726Z // month is supposed to be April
Start Date is 2022-04-20T19:25:35.726Z
How can I change the code to get the expected result?
You should do something like
function getLastWeek(date) {
var today = new Date(date);
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek;
}
// Your DATE
date = '2022-05-01'
//
var lastWeek = getLastWeek(date);
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();
var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
console.log(lastWeekDisplay);
In your code:
var now = new Date('2022-05-01'); //May 1st 2022
Dates in the format YYYY-MM-DD are parsed as UTC, so the above will create a date object representing 2022-05-01T00:00:00Z.
var day = now.getDay();
This will return the local day number. For users with a zero or positive offset, it will return 0 (Sunday) but for users with a negative offset, it will return 6 (Saturday) because their local date is still the previous day.
var diff = (day <= 2) ? (7 - 2 + day ) : (day - 2);
Given day is 0 (for me), the above sets diff to 5.
var PastTuesday = new Date();
This creates a date for "now", which for me is 17 April.
var PastWednesday = new Date(PastTuesday.setDate(now.getDate() - diff));
In the above, now.getDate returns 1, and 1 - 5 is -4, so it sets the date for PastTuesday to -4. Now PastTuesday is in April, so it is set to 4 days prior to the start of April, i.e. 27 March.
Note that this adjusts PastTuesday and creates a copy for PastWednesday at the same time.
console.log('End date is', PastTuesday.toISOString());
Shows the equivalent UTC date and time, with the time representing the time that the code was run.
PastWednesday.setDate(PastTuesday.getDate() - 6);
Sets PastWednesday to 6 days prior to PastTuesday.
Anyhow, what is required is to do everything either as UTC or local, don't mix the two.
Sticking to code as closely as possible to the original and assuming a timestamp in YYYY-MM-DD format is parsed to the function, consider the following, which does everything as local:
// Parse timestamp in YYYY-MM-DD format as local
function parseISOLocal(s = new Date().toLocaleDateString('en-CA')) {
let [y, m, d] = s.split(/\D/);
return new Date(y, m-1, d);
}
// Get week Wed to Tue prior to passed date
function getStartAndEndDates (date) {
// Parse timestamp as local
var pastTuesday = parseISOLocal(date);
// Adjust pastTuesday to previous Tuesday
var day = pastTuesday.getDay();
var diff = (day <= 2) ? (7 - 2 + day ) : (day - 2);
var pastWednesday = new Date(pastTuesday.setDate(pastTuesday.getDate() - diff));
console.log('End date is', pastTuesday.toDateString());
// Adjust pastWednesday to previous Wednesday
pastWednesday.setDate(pastTuesday.getDate() - 6);
console.log('Start Date is',pastWednesday.toDateString());
return [pastWednesday, pastTuesday];
}
// Sunday 1 May 2022
console.log(getStartAndEndDates('2022-05-01').map(d => d.toDateString()));
// Current date
console.log(getStartAndEndDates().map(d => d.toDateString()));
I'm working on a form that needs to automatically calculate the day the form is being submitted in the format ('MMDDYYYY'), and then on the click of one of two links a link, calculate the closest first day of the coming month, and the closest 15th day of the coming month.
I already created a script that pulls in the date and outputs it to a variable in the format I need, but I need help in calculating the roll forward.
Here's an example of the logic I'm thinking I need:
If the current date is 04092013, on a the button press labeled "Coming 1st of Month" a variable value of 05012013 would be calculated.
If the current date is 04092013, on a button press labeled "Coming 15th of Month" a variable value of 04152013 would be calculated.
If the current date is 04162013 or any date up to the end of the current month, on a button press labeled "Coming 15th of Month" a variable value of 05152013 would be calculated.
Look at the Date object, it should provide what you need:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
For example something like this for your first 2 buttons:
$(function() {
var date = new Date(2013, 10, 24);
$("#date").html(date.toString());
$("#date1").html((new Date(date.getYear(), date.getMonth()+1, 1)).toString());
$("#date2").html((new Date(date.getYear(), date.getMonth()+1, 15)).toString());
});
(Though I'm sure there are easier ways to do this if you look through the Date documenation)
Here is an example. If you want it back as a string, you'll have to format it at the end as desired (work with UTC ).
If you put in a date that has the same day number as you're asking of it, it returns the same day, not moving forwards a month.
var date_string = '04092013';
// MMDDYYYY
function nextNthOfMonth(date_string, n) {
var date;
// n to Int, default 1
n = (+n || 1);
// date_string to ISO 8601
date_string = // "yyyy-MM-ddTHH:mm:ssZ"
date_string.slice(4)
+ '-' + date_string.slice(0, 2)
+ '-' + date_string.slice(2, 4)
+ 'T00:00:00Z';
// construct date object
date = new Date(date_string);
// fix to desired date
if (n < date.getUTCDate()) { // adjust for month if req.
date.setUTCMonth(date.getUTCMonth() + 1);
}
date.setUTCDate(n);
return date; // or format as desired
}
nextNthOfMonth(date_string, 1);
// Wed May 01 2013 01:00:00 GMT+0100 (GMT Daylight Time)
nextNthOfMonth(date_string, 15);
// Mon Apr 15 2013 01:00:00 GMT+0100 (GMT Daylight Time)
Since you know the format of your date, split the input into parts:
var dateStr = '04092013'
var month = dateStr.substr(0,2);
var day = dateStr.substr(2,2);
var year = dateStr.substr(4,4);
The construct a new date base on the rule you want to set:
var newDate;
switch(rule)
{
case 'rule1':
newDate = new Date(year, month, 1);//first month is 0
break;
case 'rule2':
newDate = new Date(year, month, 15);//first month is 0
break;
}
remember to check if the day is greater that 15.
Try
function getDate() {
var s = document.getElementById('date').value;
if(s){
return new Date(s.substring(4), parseInt(s.substring(2, 4), 10) - 1, s.substring(0, 2))
}
}
function comingDate(date, day){
date = new Date(date);
var cday = date.getDate();
date.setDate(day);
if(cday >= day){
date.setMonth(date.getMonth() + 1)
}
return date
}
function f15(){
var d = getDate();
var next = comingDate(d, 15);
console.log(next)
}
function f1(){
var d = getDate();
var next = comingDate(d, 1);
console.log(next)
}
Demo: Fiddle
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Is there an easy way of taking a olain JavaScript Date (e.g. today) and going back X days?
So, for example, if I want to calculate the date 5 days before today.
Try something like this:
var d = new Date();
d.setDate(d.getDate()-5);
Note that this modifies the date object and returns the time value of the updated date.
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);
If you're performing lots of headachy date manipulation throughout your web application, DateJS will make your life much easier:
http://simonwillison.net/2007/Dec/3/datejs/
It goes something like this:
var d = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);
I noticed that the getDays+ X doesn't work over day/month boundaries. Using getTime works as long as your date is not before 1970.
var todayDate = new Date(), weekDate = new Date();
weekDate.setTime(todayDate.getTime()-(7*24*3600000));
If you want it all on one line instead.
5 days from today
//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 days from a specific date
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));
I wrote a function you can use.
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));
I find a problem with the getDate()/setDate() method is that it too easily turns everything into milliseconds, and the syntax is sometimes hard for me to follow.
Instead I like to work off the fact that 1 day = 86,400,000 milliseconds.
So, for your particular question:
today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))
Works like a charm.
I use this method all the time for doing rolling 30/60/365 day calculations.
You can easily extrapolate this to create units of time for months, years, etc.
get moment.js. All the cool kids use it. It has more formatting options, etc. Where
var n = 5;
var dateMnsFive = moment(<your date>).subtract(n , 'day');
Optional! Convert to JS Date obj for Angular binding.
var date = new Date(dateMnsFive.toISOString());
Optional! Format
var date = dateMnsFive.format("YYYY-MM-DD");
A few of the existing solutions were close, but not quite exactly what I wanted. This function works with both positive or negative values and handles boundary cases.
function addDays(date, days) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() + days,
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
Without using the second variable, you can replace 7 for with your back x days:
let d=new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000))
I made this prototype for Date so that I could pass negative values to subtract days and positive values to add days.
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;
};
}
So, to use it i can simply write:
var date_subtract = new Date().adjustDate(-4),
date_add = new Date().adjustDate(4);
I like doing the maths in milliseconds. So use Date.now()
var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds
and if you like it formatted
new Date(newDate).toString(); // or .toUTCString or .toISOString ...
NOTE: Date.now() doesn't work in older browsers (eg IE8 I think). Polyfill here.
UPDATE June 2015
#socketpair pointed out my sloppiness. As s/he says "Some day in year have 23 hours, and some 25 due to timezone rules".
To expand on that, the answer above will have daylightsaving inaccuracies in the case where you want to calculate the LOCAL day 5 days ago in a timezone with daylightsaving changes and you
assume (wrongly) that Date.now() gives you the current LOCAL now time, or
use .toString() which returns the local date and therefore is incompatible with the Date.now() base date in UTC.
However, it works if you're doing your math all in UTC, eg
A. You want the UTC date 5 days ago from NOW (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. You start with a UTC base date other than "now", using Date.UTC()
newDate = new Date(Date.UTC(2015, 3, 1)).getTime() + -5*24*3600000;
new Date(newDate).toUTCString(); // or .toISOString BUT NOT toString
split your date into parts, then return a new Date with the adjusted values
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);
}
Remember that the months are zero based, but the days are not. ie new Date(2009, 1, 1) == 01 February 2009, new Date(2009, 1, 0) == 31 January 2009;
Some people suggested using moment.js to make your life easier when handling dates in js. Time has passed since those answers and it is noteworthy, that the authors of moment.js now discourage its use. Mainly due to its size and lack of tree-shaking-support.
If you want to go the library route, use an alternative like Luxon. It is significantly smaller (because of its clever use of the Intl object and support for tree-shaking) and just as versatile as moment.js.
To go back 5 days from today in Luxon, you would do:
import { DateTime } from 'luxon'
DateTime.now().minus({ days: 5 });
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);
See the following code, subtract the days from the current date. Also, set the month according to substracted date.
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);
I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.
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;
}
Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.
var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");
Use 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>
The top answers led to a bug in my code where on the first of the month it would set a future date in the current month. Here is what I did,
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
I like the following because it is one line. Not perfect with DST changes but usually good enough for my needs.
var fiveDaysAgo = new Date(new Date() - (1000*60*60*24*5));
Using Modern JavaScript function syntax
const getDaysPastDate = (daysBefore, date = new Date) => new Date(date - (1000 * 60 * 60 * 24 * daysBefore));
console.log(getDaysPastDate(1)); // yesterday
A easy way to manage dates is use Moment.js
You can use add. Example
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);
Docs http://momentjs.com/docs/#/manipulating/add/
for me all the combinations worked fine with below code snipplet ,
the snippet is for Angular-2 implementation ,
if you need to add days , pass positive numberofDays , if you need to substract pass negative numberofDays
function addSubstractDays(date: Date, numberofDays: number): Date {
let d = new Date(date);
return new Date(
d.getFullYear(),
d.getMonth(),
(d.getDate() + numberofDays)
);
}
I get good mileage out of date.js:
http://www.datejs.com/
d = new Date();
d.add(-10).days(); // subtract 10 days
Nice!
Website includes this beauty:
Datejs doesn’t just parse strings, it slices them cleanly in two
If you want to both subtract a number of days and format your date in a human readable format, you should consider creating a custom DateHelper object that looks something like this :
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));
(see also this Fiddle)
To calculate relative time stamps with a more precise difference than whole days, you can use Date.getTime() and Date.setTime() to work with integers representing the number of milliseconds since a certain epoch—namely, January 1, 1970. For example, if you want to know when it’s 17 hours after right now:
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})
reference
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...
First arg is the date to start with and second is how mush day you want to increase or reduce to the date
example (1)- pass -1 to reduce date by one day
example (2)- pass 1 to increase date by one day
const EditDay = (date: Date, num: number): Date => {
return new Date(date.getTime() + num * 24 * 60 * 60 * 1000)
}
When setting the date, the date converts to milliseconds, so you need to convert it back to a date:
This method also take into consideration, new year change etc.
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) );
You can using 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
For PHP,
$date = date('Y-m-d', strtotime("-5 days")); // it shows 5 days before today.
echo $date;
Hope it will help you.
I converted into millisecond and deducted days else month and year won't change and logical
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();
Hope helps