javascript - date difference should be zero but it is 18 hours - javascript

This one has stumped me. It should be so simple I would think. I am doing some very simple date subtraction in Javascript. I am subtracting the same dates and I would think it would give zero hours, but it gives 18 hours.
let inDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime();
let outDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime();
document.getElementById('date').innerHTML = new Date(outDate - inDate);
<div id='date'>
</div>
In case it produces different results based on where you are, the result I am getting is this:
Wed Dec 31 1969 18:00:00 GMT-0600 (Central Standard Time)

This is due to your timezone. If you convert to GMT String before print it the time will be correct. (Jan 01, 1969 00:00:00)
new Date(outDate - inDate).toGMTString()
You should see the correct date.
let inDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime()
let outDate = new Date('Tue Aug 27 2019 00:00:00 GMT-0500 (Central Daylight Time)').getTime()
console.log(new Date(inDate - outDate).toGMTString())

Related

Google Apps Script return date between a range of dates in an array

I have an array of dates. I want to return the dates between January 01, 2022 and December 31, 2022.
When I run the cut below, it doesn't return anything. This is one of many different loop variations I've tried to no avail. Please help TIA
var start = new Date(2022, 0, 01); //returns Sat Jan 01 00:00:00 GMT-06:00 2022
var end = new Date(2022, 11, 01); //returns Sat Dec 31 00:00:00 GMT-06:00 2022
var arr = [Fri Dec 03 2021 00:00:00 GMT-0600 (Central Standard Time),
Fri Dec 10 2021 00:00:00 GMT-0600 (Central Standard Time),
Fri Dec 17 2021 00:00:00 GMT-0600 (Central Standard Time),
Fri Dec 24 2021 00:00:00 GMT-0600 (Central Standard Time),
Fri Dec 31 2021 00:00:00 GMT-0600 (Central Standard Time),
Fri Jan 07 2022 00:00:00 GMT-0600 (Central Standard Time),
Fri Jan 14 2022 00:00:00 GMT-0600 (Central Standard Time),
Fri Jan 21 2022 00:00:00 GMT-0600 (Central Standard Time),
Fri Jan 28 2022 00:00:00 GMT-0600 (Central Standard Time),
...](**output** NOT the actual script)
for(var i=0; i<=arr.length; i++){
if(arr[i] >= start && arr[i] <= end){
Logger.log(arr[i]);
}
}
Modification points:
From your script, I couldn't understand the value of arr. Because in your script, when you save the script, an error occurs. So I'm worried that your actual script is different from your showing script. If each value of arr is the string type like Fri Dec 03 2021 00:00:00 GMT-0600 (Central Standard Time), please enclose it using the double or single quotes.
If my guess of your script is not correct, please provide your actual script.
In order to compare the date, I think that this thread will be useful. Ref
When these points are reflected in your script, it becomes as follows.
Modified script:
var start = new Date(2022, 0, 01); //returns Sat Jan 01 00:00:00 GMT-06:00 2022
var end = new Date(2022, 11, 01); //returns Sat Dec 31 00:00:00 GMT-06:00 2022
var arr = [
"Fri Dec 03 2021 00:00:00 GMT-0600 (Central Standard Time)",
"Fri Dec 10 2021 00:00:00 GMT-0600 (Central Standard Time)",
"Fri Dec 17 2021 00:00:00 GMT-0600 (Central Standard Time)",
"Fri Dec 24 2021 00:00:00 GMT-0600 (Central Standard Time)",
"Fri Dec 31 2021 00:00:00 GMT-0600 (Central Standard Time)",
"Fri Jan 07 2022 00:00:00 GMT-0600 (Central Standard Time)",
"Fri Jan 14 2022 00:00:00 GMT-0600 (Central Standard Time)",
"Fri Jan 21 2022 00:00:00 GMT-0600 (Central Standard Time)",
"Fri Jan 28 2022 00:00:00 GMT-0600 (Central Standard Time)",
];
for (var i = 0; i <= arr.length; i++) {
if (new Date(arr[i]).getTime() >= start.getTime() && new Date(arr[i]).getTime() <= end.getTime()) {
console.log(arr[i]);
}
}
References:
Related thread
Compare two dates with JavaScript
What Tanaike mentioned is correct, it should be a string in your array and missing quotes then you can do
arr.filter(dates => new Date(dates) >= start && new Date(dates) <= end );
I was able to figure it out thanks for your input. The problem was I needed to set arr[i] to new Date(arr[i]). Below is the updated code.
var start = new Date(2022, 0, 01); //returns Sat Jan 01 00:00:00 GMT-06:00 2022
var end = new Date(2022, 11, 01); //returns Sat Dec 31 00:00:00 GMT-06:00 2022
var arr = [Fri Dec 03 2021 00:00:00 GMT-0600 (Central Standard Time),
Fri Dec 10 2021 00:00:00 GMT-0600 (Central Standard Time),
Fri Dec 17 2021 00:00:00 GMT-0600 (Central Standard Time),
Fri Dec 24 2021 00:00:00 GMT-0600 (Central Standard Time),
Fri Dec 31 2021 00:00:00 GMT-0600 (Central Standard Time),
Fri Jan 07 2022 00:00:00 GMT-0600 (Central Standard Time),
Fri Jan 14 2022 00:00:00 GMT-0600 (Central Standard Time),
Fri Jan 21 2022 00:00:00 GMT-0600 (Central Standard Time),
Fri Jan 28 2022 00:00:00 GMT-0600 (Central Standard Time),
...](**output of the array** NOT the actual script)
for(var i=0; i<=arr.length; i++){
var arrI = new Date(arr[i]);
if(arrI >= start && arrI <= end){
Logger.log(arrI);
}
}

How to increase the date when moving to the other month

I have a date set which I am filling it with the number of current week and year:
dateSets(week, year) {
let fistDayOfTheWeek = '';
if(this.currentWeekNumber === this.getWeekNumber(new Date())) {
fistDayOfTheWeek = new Date();
} else {
fistDayOfTheWeek = this.getDateOfWeek(week, year);
}
let sunday = new Date(fistDayOfTheWeek);
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
const dates = [];
const diff = sunday.getDate() - fistDayOfTheWeek.getDate();
for (let i = 0; i <= diff; i++) {
const upDate = new Date();
upDate.setDate(fistDayOfTheWeek.getDate() + i);
dates.push(upDate);
}
console.log(dates)
return dates;
},
So apperantly my dateSet function works like if it is not monday then show the dates from today to sunday and from next week from monday to sunday. But what is wrong in this function is it doesnt push when the month is changed. So for 4 weeks console.log(dates) displays:
[Tue Aug 10 2021 16:22:43 GMT+0200 (Central European Summer Time),
Wed Aug 11 2021 16:22:43 GMT+0200 (Central European Summer Time), Thu
Aug 12 2021 16:22:43 GMT+0200 (Central European Summer Time), Fri Aug
13 2021 16:22:43 GMT+0200 (Central European Summer Time), Sat Aug 14
2021 16:22:43 GMT+0200 (Central European Summer Time), Sun Aug 15
2021 16:22:43 GMT+0200 (Central European Summer Time)]
[Mon Aug 16 2021 16:22:46 GMT+0200 (Central European Summer Time),
Tue Aug 17 2021 16:22:46 GMT+0200 (Central European Summer Time), Wed
Aug 18 2021 16:22:46 GMT+0200 (Central European Summer Time), Thu Aug
19 2021 16:22:46 GMT+0200 (Central European Summer Time), Fri Aug 20
2021 16:22:46 GMT+0200 (Central European Summer Time), Sat Aug 21
2021 16:22:46 GMT+0200 (Central European Summer Time), Sun Aug 22
2021 16:22:46 GMT+0200 (Central European Summer Time)]
[Mon Aug 23 2021 16:22:47 GMT+0200 (Central European Summer Time),
Tue Aug 24 2021 16:22:47 GMT+0200 (Central European Summer Time), Wed
Aug 25 2021 16:22:47 GMT+0200 (Central European Summer Time), Thu Aug
26 2021 16:22:47 GMT+0200 (Central European Summer Time), Fri Aug 27
2021 16:22:47 GMT+0200 (Central European Summer Time), Sat Aug 28
2021 16:22:47 GMT+0200 (Central European Summer Time), Sun Aug 29
2021 16:22:47 GMT+0200 (Central European Summer Time)]
[]
As you see since after 3 weeks, the month will be changed to september and I think that's why it comes to an empty array.
I dont know if it is necessary but in any case here are the other functions that I used:
getDateOfWeek(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
return ISOweekStart;
}
getWeekNumber(date) {
const temp_date = new Date(date.valueOf());
const dayn = (date.getDay() + 6) % 7;
temp_date.setDate(temp_date.getDate() - dayn + 3);
const firstThursday = temp_date.valueOf();
temp_date.setMonth(0, 1);
if (temp_date.getDay() !== 4)
{
temp_date.setMonth(0, 1 + ((4 - temp_date.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstThursday - temp_date) / 604800000);
},
PS: currentWeekNumber is increasing everytime when the button is clicked.
Your issue is here:
const diff = sunday.getDate() - fistDayOfTheWeek.getDate();
when you get to the end of the month of say August, the next Sunday is 5 Sep and the first day of the week is 30 August, so diff is -25 and in the test:
for (let i = 0; i <= diff; i++) {
i is less than diff from the start so nothing is added to the array.
One fix is to get the number of days until the next Sunday and iterate for that many days, e.g.
// Return an array of dates from tomorrow until the
// following Sunday.
function getDatesToSunday(date = new Date()) {
// Copy date so don't affect original
let d = new Date(+date);
// Get the number of days until the next Sunday
let count = 7 - d.getDay();
// Create array of Dates
let dates = [];
while (count--) { 
dates.push (new Date(d.setDate(d.getDate() + 1)));
}
return dates;
}
console.log('Given Sun 29 Aug 2021:');
getDatesToSunday(new Date(2021, 7, 29))
.forEach(d => console.log(d.toDateString()));
console.log('Rest of this week, or next if today is Sunday:');
getDatesToSunday()
.forEach(d => console.log(d.toDateString()));
If the supplied date is Saturday, the above returns an array of just Sunday. If the supplied date is Sunday, it returns an array of the following Monday to Sunday, etc.
If you want to get multiple weeks of dates, add a second parameter, say weeks that defaults to 1, then add (weeks - 1) * 7 to count before the while loop. Test weeks first to ensure it's 1 or greater (starting a decrementing while loop with a negative number is not a good idea).
Or you can just keep adding days until Sunday:
const getDatesToSunday = (date = new Date()) => {
// Setup
let year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
dates = [];
// Add dates from tomorrow until Sunday
do {
dates.push(new Date(year, month, ++day));
} while (dates[dates.length - 1].getDay());
return dates;
};
getDatesToSunday().forEach(d=>console.log(d.toDateString()));

How to use .replace to replace the string in a array

need to replace GMT+0530 (India Standard Time) to IST
dynamically for multiple array list
for now my array list has 6 entries. need to replace for all the array list .
function getTimeAccordingtoTimeZone(utc){
utc = new Date(Date.parse(utc));
var dateUTC = utc ;
var dateIST = new Date(dateUTC);
//date shifting for IST timezone (+5 hours and 30 minutes)
var current_time_zone = getCurrentTimeZone();
var hour_diff = parseInt(current_time_zone);
var minute_diff = current_time_zone - hour_diff;
minute_diff = minute_diff*60;
dateIST.setHours(dateIST.getHours() + hour_diff);
dateIST.setMinutes(dateIST.getMinutes() + minute_diff);
var new_date = dateIST;
return new_date;
}
new_date returns
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
Tue Jan 15 2019 22:49:04 GMT+0530 (India Standard Time)
I'd propose you use moment JS to format the string.
In your case, the following code will help you:
const moment = require('moment');
date = moment();
const dateString = `${date.format('ddd MMM DD YYYY HH:mm:ss')} IST`
console.log(dateString);
MomentJs Documentation

date loop increment and growing variable ( mootools )

Can someone please take a look at this with fresh eyes.
var start_date = Date.parse('2013-07-01');
var i_date = Date.parse('2013-07-5');
console.log(start_date + '---before loop ');
for (var n = start_date; n < i_date; n.increment()) {
console.log(start_date + '---inside loop ');
}
console.log(start_date + '---after loop ');
This code produces this:
Mon Jul 01 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---before loop
Mon Jul 01 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Tue Jul 02 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Wed Jul 03 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Thu Jul 04 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Fri Jul 05 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---after loop
Why does start_date variable grow?
(fiddle here if needed)
The problem is that n and start_date are pointing to the same object. You need to clone the date by creating new Date object, for example:
n = new Date(start_date);
Updated demo.
Example:
> a = new Date()
Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
> b = a
Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
> c = new Date(a)
Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
// Do some stuff with "a"
> a
Sat Jun 29 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
> b
Sat Jun 29 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
> c
Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)

31 days in February in Date object

This code should log all days for given month:
var date = new Date(2012,2,1);
var thisMonth = date.getMonth();
while(date.getMonth()==thisMonth) { // 31 steps ???
console.log(date.getMonth(),date.getDate());
date.setDate(date.getDate()+1);
}
It works well for every month but February. Any ideas where is the catch?
Note the month parameter is 0-indexed, so your code is about March not February.
The doc:
month
Integer value representing the month, beginning with 0 for January to
11 for December.
Use new Date(2012,1,1); month is zero-based ;-)
This is pretty interesting:
new Date('2014-02-28'); // Fri Feb 28 2014 01:00:00 GMT+0100
new Date('2014-02-29'); // Sat Mar 01 2014 01:00:00 GMT+0100
new Date('2014-02-30'); // Sun Mar 02 2014 01:00:00 GMT+0100
new Date('2014-02-31'); // Mon Mar 03 2014 01:00:00 GMT+0100
new Date('2014-02-32'); // Invalid Date

Categories

Resources