I have 10 value like this ( I use new Date() to create it ) :
Wed Jun 14 2017 18:51:33
Wed Feb 7 2017 18:51:33
Wed Apr 10 2017 18:51:33
Wed Jun 10 2017 18:51:33
Wed Jun 1 2017 18:51:33
....
How can I get value of last 5 day
you can get past dates by decrementing date you get from new Date() function.
check below code.
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
you can do date formatting in yesterday too.
In Javascript,
add dates to one array, iterate them
var datesArray = []; //add dates to this array
var lastfivedays = [];
datesArray.forEach(function(checkdate){
var currentDate = new Date();
var timeDiff = currentDate.getTime() - checkdate.getTime();
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if(diffDays == -5){
lastfivedays.push(checkdate)
}
});
lastfivedays array contains dates of last 5 day
Related
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 have a javascript function that takes in a number X and a date, and returns a new Date that is X number of days away:
function addDays(theDate, numDaysToAdd) {
var newDate = new Date();
return new Date(newDate.setDate(theDate.getDate() + numDaysToAdd));
}
I pass it a day that is Sat Jul 02 2016 16:03:06 GMT-0700 (Pacific Daylight Time) and a number 7, but the result I got was Thu Jun 09 2016 16:05:32 GMT-0700 (Pacific Daylight Time). Why is it giving me the correct date but wrong month?
The problem is that newDate is always created from the current date (new Date()). In other words, if this function is executed in June it will produce a date in June, then try to set a the day of the month as a offset from the input date.
You need to construct newDate as a copy of theDate:
function addDays(theDate, numDaysToAdd) {
var newDate = new Date(theDate);
newDate.setDate(theDate.getDate() + numDaysToAdd);
return newDate;
}
var d = new Date('Sat Jul 02 2016 16:03:06 GMT-0700 (Pacific Daylight Time)');
console.log(addDays(d, 7).toString());
You can add number of milliseconds to given date and it will generate correct date.
getTime() returns milliseconds from epoch.
offset = numDaysToAdd * 24 * 60 * 60 * 1000;
24: Hours in a day
60: Minutes in an hour
60: seconds in a minute
1000: milliseconds in a second
Date constructor takes milliseconds from epoch
function addDays(theDate, numDaysToAdd) {
var start = theDate.getTime();
var offset = numDaysToAdd * 24 * 60 * 60 * 1000;
return new Date(start + offset);
}
var today = new Date();
console.log(today, addDays(today, 10));
I am trying to add two dates:
date start Fri Apr 26 2013 16:08:03 GMT+0100 (Paris, Madrid)
+
date periode Fri Apr 26 2013 00:10:00 GMT+0100 (Paris, Madrid)
I used this code:
var periode=$("#dure").val();
var start = $("#start").val()
var end =$("#end").val();
var dateStart= new Date(start);
console.log('start');
console.log(dateStart);
var date=dateStart.format('yyyy-mm-dd');
per=date+' '+periode;
var datePeriode= new Date(per);
console.log('datePeriode');
console.log(datePeriode);
var dateEnd= dateStart.getTime()+datePeriode.getTime();
console.log('dateEnd');
console.log(dateEnd);
In my JavaScript console, I get:
dateDebut
Fri Apr 26 2013 16:33:11 GMT+0100 (Paris, Madrid)
datePeriode
Fri Apr 26 2013 00:15:00 GMT+0100 (Paris, Madrid)
dateEnd
2733922091000
How can I fix that? Am I missing something?
If you want to add a time period to a date, you basically have to convert both of them into milliseconds.
var date = new Date();
var dateMillis = date.getTime();
//JavaScript doesn't have a "time period" object, so I'm assuming you get it as a string
var timePeriod = "00:15:00"; //I assume this is 15 minutes, so the format is HH:MM:SS
var parts = timePeriod.split(/:/);
var timePeriodMillis = (parseInt(parts[0], 10) * 60 * 60 * 1000) +
(parseInt(parts[1], 10) * 60 * 1000) +
(parseInt(parts[2], 10) * 1000);
var newDate = new Date();
newDate.setTime(dateMillis + timePeriodMillis);
console.log(date); //eg: Fri Apr 26 2013 08:52:50 GMT-0700 (MST)
console.log(newDate); //eg: Fri Apr 26 2013 09:07:50 GMT-0700 (MST)
Convert datePeriod to milliseconds instead of making it into a date object for your addition.
You need to convert the sum to a date. getTime() is in milliseconds since 1-1-1970. So you want to do.
var ending = new Date();
ending.setTime(dateEnd);
console.log(ending);
setTime will set the date properly for you.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setTime
According to this question, I wrote "my code" (without Math.abs, I don't need it) :
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date("2011", "09", "28"); // 28 september 2011
var secondDate = new Date("2011", "09", "30"); // 30 september 2011
var notti = ((secondDate.getTime() - firstDate.getTime()) / (oneDay));
if (notti < 1)
notti = 1;
else
notti = Math.round(notti);
alert(notti);
and it print 2 (correct).
Now, If I do this :
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date("2011", "09", "28"); // 28 september 2011
var secondDate = new Date("2011", "10", "01"); // 01 october 2011
var notti = ((secondDate.getTime() - firstDate.getTime()) / (oneDay));
if (notti < 1)
notti = 1;
else
notti = Math.round(notti);
alert(notti);
it print 4. Why 4? It should be 3...
Do you know about this problem?
The month argument in the date constructor (and other date methods) runs from [0.11] not [1..12] so:
new Date("2011", "09", "28"); // 28 september 2011
is actually Fri Oct 28, not September.
Javascript months are zero based. So October has 31 days.
new Date("2011", "9", "31"); // October 31st
Because...
new Date("2011", "09", "28").toString()
... returns:
Fri Oct 28 2011 00:00:00 GMT-0400 (EDT)
This is because JavaScript Data is based on the Java Date object, which is a mess. See also "Puizzle 61: The Dating Game" in the book JavaPuzzlers for an explanation.
I have lead_creat_date and I need to compare it against 20 days before date ( let's say today is aug-4-2011, than I need july-14-2011). So comparison against lead_creat_date and July-14-2011.
if ( lead_creat_date > july-14-2011)
{
alert('lead_creat_date is greater');
}
How can I do this comparison in JavaScript?
I'm trying using the JavaScript date object. I did get one number for 20 days before date, using setDate() & getDate() function but I don't know how to convert lead_creat_date into a JavaScript date() object.
Thanks.
It's likely you can use the Date.parse() method.
It really depends on your date format.
I'll assume lead_creat_date is a Date object, seeing as it's not clear...
It depends on how accurate you need to be. You can do something like this, which will go back exactly 20 days, to the millisecond.
var now = new Date().getTime() - 20 * 24 * 60 * 60 * 1000;
if (lead_creat_date > now) {
alert('lead_creat_date is greater');
}
If you only care about the day, you could probably do this
var now = new Date().getTime() - 20 * 24 * 60 * 60 * 1000;
now = new Date(now.toDateString());
if (lead_creat_date > now) {
alert('lead_creat_date is greater');
}
References:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toDateString
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime
To convert a string to a date, convert the parts to numbers to use as input to the Date constructor. e.g. if your date is July-14-2011 then you can convert it using:
var dateString = 'July-14-2011';
var months = {january:0, february:1, march:2, april:3,
may:4, june:5, july:6, august:7, september:8,
october:9, november:10, december:11};
var dateBits = dateString.split('-');
var monthNumber = months[dateBits[0].toLowerCase()];
// Date object for date string
var date = new Date(dateBits[2], monthNumber, dateBits[1]);
// 20 days prior
date.setDate(date.getDate() - 20); // 24 Jun 2011
Edit
If your date format is 8/27/2009 10:23:00 AM the you can convert to a date using:
var dateString = '8/3/2011 10:23:00 AM';
var dateBits = dateString.split(/[ \/]/);
var date = new Date(dateBits[2], dateBits[0] - 1, dateBits[1]);
// 20 days prior
date.setDate(date.getDate() - 20); // 14 Jul 2011
alert(date);
If you need to include the time, you can include it using the same strategy, e.g.
var dateString = '8/3/2011 10:23:00 AM';
var dateBits = dateString.split(/[ \/:]/);
if (dateBits[6].toLowerCase() == 'pm') {
dateBits[3] = +dateBits[3] + 12;
}
// Thu 14 Jul 2011 10:23:00
var date = new Date(dateBits[2], dateBits[0] - 1, dateBits[1] - 20,
dateBits[3], dateBits[4], dateBits[5]);
and as a function:
function offsetDate(dateString, offset) {
var dateBits = dateString.split(/[ \/:]/);
if (dateBits[6].toLowerCase() == 'pm') {
dateBits[3] = +dateBits[3] + 12;
}
return new Date(dateBits[2], dateBits[0] - 1,
+dateBits[1] + +offset,
dateBits[3], dateBits[4], dateBits[5]);
}
// Thu 14 Jul 2011 10:23:00
alert(offsetDate('8/3/2011 10:23:00 AM', -20));
// Tue 23 Aug 2011 22:23:00
alert(offsetDate('8/3/2011 10:23:00 PM', +20));
// Wed 18 Jan 2012 10:23:00
alert(offsetDate('12/29/2011 10:23:00 AM', +20));