How to display time range on iteration? - javascript

I am trying to run a for loop that has to loop 8 times. On each iteration I want the loop to increment the value by +1 hour.
The final output should be in this time format:
opening hours:
08:00, 09:00, 10:00,11:00, 12:00, 13:00, 14:00, 15:00,16:00
In this case timediff mentioned in the for...loop holds the value of 8.
var minutesToAdd = 60;
var currentDate = new Date("2022-04-10 08:00:00");
var futureDate = new Date(currentDate.getTime() + minutesToAdd * 120000).toLocaleTimeString();
for (let i = 0; i < timeDiff; i++) {
console.log(futureDate, 'futureeee date');
}

Your code never updates futureDate in the loop. Also, when you expect to print 08:00 in the example, you should print currentDate when no minutes have been added yet.
I would also suggest you use the native function setMinutes and getMinutes to add a number of minutes to a date object.
You say that timeDiff has a value of 8, but then you say you want 9 outputs (8:00 ... 16:00), so you'll need an additional iteration.
Finally, to get the hh:mm output format, there are several solutions. One is to choose a locale that uses a format that is close to what you need, and express you want the short format (without seconds):
let timeDiff = 9; // One more to also output 16:00
let minutesToAdd = 60;
let currentDate = new Date("2022-04-10 08:00:00");
for (let i = 0; i < timeDiff; i++) {
console.log(currentDate.toLocaleTimeString("en-SE", { timeStyle: "short" }));
currentDate.setMinutes(currentDate.getMinutes() + minutesToAdd);
}

You can then use a simple for-loop to iterate from 0 up to and including timeDiff, incrementing each iteration by 1.
for (let hours = 0; hours <= timeDiff; hours += 1) {
// ...
}
Instead of a starting date we'll start with a timestamp Date.parse("2022-04-10 08:00:00"). This allows us to add the time from the loop to the timestamp and create a new date.
const date = new Date(currentTimestamp + hours*HOURS);
To only display the time I've taken the liberty of using the solution provided by the answer of trincot.
const MILLISECOND = 1 , MILLISECONDS = MILLISECOND;
const SECOND = 1000*MILLISECONDS, SECONDS = SECOND ;
const MINUTE = 60*SECONDS , MINUTES = MINUTE ;
const HOUR = 60*MINUTES , HOURS = HOUR ;
const timeDiff = 8;
var currentTimestamp = Date.parse("2022-04-10 08:00:00");
for (let hours = 0; hours <= timeDiff; hours += 1) {
const date = new Date(currentTimestamp + hours*HOURS);
console.log(date.toLocaleString(undefined, { timeStyle: "short" }));
}

Related

How can I get the difference between two dates in hours, omitting the hours on weekends?

I need a function to check how many hours have passed between two dates, but if for example there is a weekend in between, then skip those hours.
Date 1: moment('2022-05-27 20:00:00).tz('UTC')
Date 2: moment('2022-05-30 20:00:00).tz('UTC')
Expected output: 24 hours
I get 25 if I do i <= n and 24 when I do i < n
But I do not use moment
Note that this should work across daylight savings changes in the locale you are in
const d1 = new Date('2022-05-27 20:00:00')
const d2 = new Date('2022-05-30 20:00:00')
console.log(d1, d2)
let hours = 0;
for (let i = d1.getTime(), n = d2.getTime(); i < n; i += 3600000) {
const d = new Date(i);
if (![0, 6].includes(d.getDay())) hours++;
}
console.log(hours)

Javascript Loop Next 10 Days

I have the following code which I want to return an incremental date for the next 10 days
const startingDay = new Date('2021-10-29');
const thisDay = new Date(startingDay);
for(var i=1; i<10; i++) {
thisDay.setDate(startingDay.getDate() + i);
console.log(thisDay);
}
which is great, but for some reason as soon as it hits Oct 31, it starts going up in months rather than days.
Why would that be?
Thanks
Altering your logic slightly will give you the desired behaviour, setDate() will not work the way you expect with multiple calls to the same date instance.
The reason is that, starting with November 01, at iteration #4, we'll be setting the date to 33 (29 + 4). The logic used by setDate will be to advance the date to the next month, December, since November has only 30 days, then advancing another 2 days to December 3. The same effect will happen for subsequent iterations.
By re-creating the thisDay variable on each iteration, the logic used by setDate will work as expected.
const startingDay = new Date('2021-10-29');
for(var i= 1; i < 10; i++) {
let thisDay = new Date(startingDay);
thisDay.setDate(startingDay.getDate() + i);
console.log(thisDay);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
for(var i=1; i<10; i++) {
thisDay.setDate(startingDay.getDate() + i);
Since you're looping from 1 to i < 10, you'll add more days as the loop progresses.
I want to return an incremental date for the next 10 days
So why update thisDay with the startingDay.getDate() + i if you can just use thisDay.getDate() + 1:
const startingDay = new Date('2021-10-29');
const thisDay = new Date(startingDay);
for(var i=1; i<10; i++) {
thisDay.setDate(thisDay.getDate() + 1);
console.log(thisDay);
}
"2021-10-30T00:00:00.000Z"
"2021-10-31T00:00:00.000Z"
"2021-11-01T01:00:00.000Z"
"2021-11-02T01:00:00.000Z"
"2021-11-03T01:00:00.000Z"
"2021-11-04T01:00:00.000Z"
"2021-11-05T01:00:00.000Z"
"2021-11-06T01:00:00.000Z"
"2021-11-07T01:00:00.000Z"
Read the docs for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate .
It will automatically switch to the next or previous month if you provide a value that is out of range for the current month. This makes it easier to jump between months when adding days.
But the way you've coded your example, you always start from the day of the original date, but edit the second date:
i:1 | date = 2021-10-29 -> set day to 30th -> date = 2021-10-30
i:2 | date = 2021-10-30 -> set day to 31st -> date = 2021-10-31
i:3 | date = 2021-10-31 -> set day to 32nd -> date = 2021-11-01, since oct only has 31 days
i:4 | date = 2021-11-01 -> set day to 33rd -> date = 2021-12-03, since nov has 30 days, so adding 33 days to the first of nov, gives us 3rd of december
To avoid the incorrect day due to month switching you can solve it using Date() itself.
const startingDay = new Date('2021-10-29');
let thisDay = new Date(startingDay);
for(let i = 1; i<10; i++) {
thisDay = new Date(Date.now() + i * 24 * 60 * 60 * 1000);
console.log(thisDay.getDate());
}

How to get full day hour date format in node js

Hi I want to print a list of today date starting with 0th hour till 24 hour
const date = new Date().toISOString();
console.log(date) //21-06-01T17:09:40.766Z
the above code gives me current ISO dateTimestamp
I want dateTimestamp staring from 21-06-01T00:00:00Z,........,21-06-01T24:00:00Z
How to get that any simple way is available
This is how you do it using only JavaScript:
var currentTimeStamp = new Date().getTime() // get current timestamp
var firstTime = (currentTimeStamp - (currentTimeStamp % 86400000)) // get the first hour of the day
var totalMilliSecsInHour = 3600000 // milliseconds in one hour
for (let i = 0; i < 24; i++) {
console.log(new Date(firstTime))
firstTime += totalMilliSecsInHour // after getting the date increment the timestamp
}
You can do it with luxon.
First get the first hour of the day, then only sum one hour until 24.
import { DateTime } from 'luxon';
const allHours = []; // Array of hours
const fistHour = DateTime.utc().startOf('day'); // this is the 00:00
const totalHours = 24;
let currentHour = 0;
for (currentHour = 0; currentHour < totalHours; currentHour++) {
const startHourDT = fistHour.plus({ hours: currentHour });
allHours.push(startHourDT.toJSDate());
}
console.log(allHours);
Dont forget instal Luxon fist with npm i luxon --save.
Hope it help you
PS. I don speak english very well.

Creating an array of dates between 2 dates

I have 2 dates: startdate and enddate. End date is always a day less than the startdate. So if my start day is 19th, the end date would be on the 18th of next month.
I am trying to create an array of number of days in between the 2 dates.
(It goes from 19th to 18th and then 18th to 18th of every month to calculate the difference)
Example
8/19/2018 - 9/18/2018 = 30 days
9/18/2018 - 10/18/2019 = 30 days
10/18/2018 - 11/18/2018 = 31 days
array = [30,30,31]
I am using the following code to calculate days difference between the dates.
function daysBetweenArrears (date1, date2){
date1.setDate(date1.getDate() );
date2.setDate(date2.getDate() - 1);
var Diff = Math.abs(date2.getTime() - date1.getTime());
var TimeDifference = Math.round(Diff / (1000 * 3600 * 24));
return TimeDifference;
}
The following code for creating the array
if (document.getElementById("endDate"))
y = document.getElementById("endDate").value;
if (document.getElementById("startDate"))
z = document.getElementById("startDate").value;
var dateArr = getDateArray(z, y);
var dayCountArr = "";
var b = [];
for (var x = 0; x < dateArr.length-1; x++)
{
dayCountArr += daysBetweenArrears(dateArr[x], dateArr[x+1], ",");
b.push(daysBetweenArrears(dateArr[x], dateArr[x+1]));
}
The issue is that when i set the date as following, it is giving me incorrect output. The problem is that it is setting the dates incorrectly whenever it goes to the next month. I am not sure what i am doing wrong here. Any help is greatly appreciated. Thank you.
date2.setDate(date2.getDate() - 1);
You can do this using moment. Hope this helps.
const start = "8/19/2018";
const end = "11/18/2018 ";
const dates = [];
const mstart = moment(new Date(start));
const mend = moment(new Date(end));
for (let i = 0; mstart < mend ; i++) {
const daysInMonth = mstart.daysInMonth() + (i === 0 ? -1 : 0);
dates.push(daysInMonth);
mstart.add(1, 'M');
}
console.log(dates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
You can update your function daysBetweenArrears
const daysBetweenArrears = (date1, date2) => {
const time1 = new Date(date1).getTime();
const time2 = new Date(date2).getTime();
const diff = Math.abs(time2 - time1);
return Math.round(diff/(1000*60*60*24));
};
console.log(daysBetweenArrears('8/18/2018', '9/18/2018'));
console.log(daysBetweenArrears('6/18/2018', '7/18/2018'));

How to get the 7 days in a week with a currentDate in javascript?

(first, sorry for my bad english, i'm a beginner)
I have a chart of percent by date. I would like to display every day of the current week in the x-axis.
So, i tried to find how to get the seven days of the week.
that's what i have :
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();//to set first day on monday, not on sunday, first+1 :
var firstday = (new Date(curr.setDate(first+1))).toString();
for(var i = 1;i<7;i++){
var next = first + i;
var nextday = (new Date(curr.setDate(next))).toString();
alert(nextday);
}
the alert begins well...until the end of the month. That's what i got :
1 : "Mon 27 Feb 2012 ..."
2 : "Tue 28 Feb 2012 ..."
3 : "Wed 29 Feb 2012 ..."
4 : "Thu 01 Mar 2012 ..."
5 : "Sat 31 Mar 2012 ..."
6 : "Sun 01 Apr 2012 ..."
So, as you can see, it switches the friday and... strangely it switch to the good date...4 weeks later...
So, do you have a better solution for me, or maybe you could just help me and say what is the problem.
Thank you!
I'm afraid you have fallen into one of the numerous traps of object mutation. :)
The problem is that, in the line "var nextday = ...", you are changing the date saved in "curr" on every iteration by calling setDate(). That is no problem as long as next is within the range of the current month; curr.setDate(next) is equivalent to going forward one in this case.
The problems begin when next reaches 30. There is no February 30, so setDate() wraps around to the next month, yielding the 1st of March - so far so good. Unfortunately, the next iteration calls curr.setDate(31), and as curr is the 1st of March (remember that the object referenced by curr is changed in each iteration), we get... March 31! The other strange values can be explained the same way.
A way to fix this is to copy curr on each iteration and then call setDate(), like so:
for (var i = 1; i < 7; i++) {
var next = new Date(curr.getTime());
next.setDate(first + i);
alert(next.toString());
}
Thank you all,
I understood that everytime i change the curr value and that was the problem.
All your solutions are working, but i'll prefer the simplest one, the one from #denisw, which I copy there for anybody else with the same problem :
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
var firstday = (new Date(curr.setDate(first+1))).toString();
for(var i = 1; i < 7; i++) {
var next = new Date(curr.getTime());
next.setDate(first+i);
alert(next.toString());
}
Once again, thank you all, for your quick answers and your help!
You can add date and day. The former goes from 1 to 28..31 and the latter from 0 to 6. What should the Date type do if you set the date to -3?
The solution is to convert all values to milliseconds.
var ONE_DAY_IN_MILLIS = 1000*60*60*24;
var curr = new Date();
// Get offset to first day of week
// Note: Depending on your locale, 0 can be Sunday or Monday.
var offset = curr.getDay() * ONE_DAY_IN_MILLIS;
// Date at the start of week; note that hours, minutes and seconds are != 0
var start = new Date( curr.getTime() - offset );
for( var i=0; i<7; i++ ) {
var nextDay = new Date( start.getTime() + ( i * ONE_DAY_IN_MILLIS ) );
...
}
The problem is that you are modifying your curr date and creating a new date at the same time. There are two ways to do this:
Either never modifiy your curr date object and create new Dates:
var msInDay = 1000 * 60 * 60 * 24;
function addDays(date, days) {
return new Date(date.getTime() + days * msInDay);
}
var curr = new Date();
var first = addDays(curr, -curr.getDay() + 1);
alert(first);
for(var i = 1; i<7; i++) {
var next = addDays(first, i);
alert(next);
}
Or modify your curr date object consistently:
var curr = new Date();
curr.setDate(curr.getDate() - curr.getDay() + 1);
alert(curr);
for(var i = 1; i<7; i++) {
curr.setDate(curr.getDate() + 1);
alert(curr);
}
​
let curr = new Date;
let week = []
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
week.push(day)
}
console.log('week:', week);
jsfidde: https://jsfiddle.net/sinh_nguyen/v9kszn2h/4/

Categories

Resources