Moment-Range: Need to divide day into 15 minute slices - javascript

At present I can only divide the day into 1 hour blocks.
But I need the ranges in 15 minute steps.
Moment-Range Documentation
This is my present code:
function iterateOverDayByIntervalOfHours(inputJSON){
var day = getDayFromFromJSON(inputJSON);
var start = new Date("2016-05-04T00:00:00.000Z");
var end = new Date("2016-05-04T23:59:59.999Z");
var range = moment.range(start, end);
var slices = {}
range.by( 'hours', function(moment) {
console.log(moment);
slices["moment"] = moment
console.log("slices: "+ slices["moment"]);
var ROTsAccumulatedForInterval = getAccumulatedROTForTimeIntervall(range);
var NumberOfFlightsForInterval = getNumberOfFlightsForTimeIntervall(range);
});
console.log(slices["moment"]);
}
any ideas?

Here is another way using moment lib with moment-range extension:
const day_start = moment().startOf('day').hours(7); // 7 am
const day_end = moment().startOf('day').hours(22) // 10 pm
const day = moment.range(day_start, day_end)
const time_slots = Array.from(day.by('minutes', {step: 30}))
in
Array.from(day.by('minutes', {step: 30}))
You can change 'minutes' for hours, days, weeks
and step for how many minutes/hours/days you want to chunk by.
return value will be
[ moment("2017-10-20T07:00:00.000"),
moment("2017-10-20T07:30:00.000"),
moment("2017-10-20T08:00:00.000"),
moment("2017-10-20T08:30:00.000"),
moment("2017-10-20T09:00:00.000"),
moment("2017-10-20T09:30:00.000"),
...
moment("2017-10-20T19:30:00.000"),
moment("2017-10-20T20:00:00.000"),
moment("2017-10-20T20:30:00.000"),
moment("2017-10-20T21:00:00.000"),
moment("2017-10-20T21:30:00.000"),
moment("2017-10-20T22:00:00.000") ]

This doesn't use moment and it's not implemented in your function yet, but this is how I would try to get an object of 15min-chunks. I hope, this is what you are looking for.
var start = new Date("2016-05-04T00:00:00.000Z");
var end = new Date("2016-05-04T23:59:59.999Z");
var slices = {};
var count = 0;
var moment;
while (end >= start) {
start = new Date(start.getTime() + (15 * 60 * 1000));
slices[count] = start;
count++;
}
console.log(slices);

You can also use something like this.
// Take a starting point
const start = moment('00:00:00', 'HH:mm:ss');
// Take a end point
const end = moment('23:59:59', 'HH:mm:ss');
const timeSeries = [];
while (start.isSameOrBefore(end)) {
// add 15 minutes to the starting point
timeSeries.push(start.add(15, 'm').format('HH:mm'));
}
console.log(timeSeries);

Too late but might be helpful, I'm doing the following to divide a day into hour date ranges.
using lodash and moment
const generateDayHours = (x = 24) => {
const hoursArr = [];
_.times(x, (i) => {
hoursArr.push({
fromDate: moment().startOf('day').add(x - (i + 1), 'hour').startOf('hour'),
toDate: moment().startOf('day').add(x - (i + 1), 'hour').endOf('hour')
});
});
return hoursArr;
};
jsbin to test

Related

How to get the number of days with dates of a given week number by using JavaScript

I want to show them in a loop
Having an understanding of JavaScript & jQuery.
I have done to get the week number in a loop by using this code, for now, I want to get all days with dates of the given week number
function printWeekNumber() {
var dateFrom =
document.getElementById("txtFrom").value;
var dateF = new Date(dateFrom);
var resultFrom = dateF.getWeekNumber();
Date.prototype.getWeekNumber = function () {
var oneJan =
new Date(this.getFullYear(), 0, 1);
// calculating number of days
//in given year before given date
var numberOfDays =
Math.floor((this - oneJan) / (24 * 60 * 60 * 1000));
// adding 1 since this.getDay()
//returns value starting from 0
return Math.ceil((this.getDay() + 1 + numberOfDays) / 7);
}
function printWeekNumber() {
var dateFrom =
document.getElementById("txtFrom").value;
var dateF = new Date(dateFrom);
var resultFrom = dateF.getWeekNumber();
var dateTo =
document.getElementById("txtTo").value;
var dateT = new Date(dateTo);
var resultTo = dateT.getWeekNumber();
for (var i = resultFrom; i <= resultTo; i++) {
alert(i);
}
}
}
Please help me I am stuck in this step.

Array of days in between months

I have two dates: Startdate and enddate
startdate = "10/10/2018" enddate = "03/09/2019"
I am trying to create an array of dates between those 2 dates. I have the following code.
function getDateArray (start, end) {
var arr = [];
var startDate = new Date(start);
var endDate = new Date(end);
endDate.setMonth( endDate.getMonth());
while (startDate <= endDate) {
arr.push(new Date(startDate));
startDate.setMonth(startDate.getMonth() + 1);
}
return arr;
}
Then calculate the number of days between those months in between.
10/10/2018 to 11/10/2018 = 30 days
11/10/2019 to 12/10/2018 = 30 days or so depending on number of days between the 2 dates and then create an array of the dates.
[30,30,31....till end date]
function daysBetween(date1, date2 )
{
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var dayDifference = Math.ceil(timeDiff / (1000 * 3600 * 24));
return dayDifference;
}
I tried the following code and it's returning the array of number of dates however, it's not accurate. It keeps returning 32 days in October. The output it's giving right now is as follows. I am not sure what i am doing wrong here but it looks like it's only going till February and displaying the result.
Any help will be appreciated. Thank you.
Output: [32,30,31,31,28]
var dateArr = getDateArray(z, y);
console.log(dateArr);
var dayCounts = "";
for (var x = 0; x < dateArr.length-1; x++)
{
dayCounts += daysBetween(dateArr[x], dateArr[x+1]);
}
console.log("datearrlength" + dateArr.length);
console.log(dayCounts);
i think this will work for you,
Date.prototype.addDay= function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getDateBwStartandEnd(sdate, edate) {
var dateArray = new Array();
var currentDate = sdate;
while (currentDate <= edate) {
dateArray.push(new Date (currentDate));
currentDate = currentDate.addDay(1);
}
return dateArray;
}
** Shamelessly copied from web, but this works fine for me.
While the following doesn't answer your question it is an alternative approach to the overall problem you are attempting to solve.
One approach would be to simply get the time difference between the two dates and then divide by the number of microseconds in a day. As you will notice though it is not exact and so a floor is used to get the days. There are other concerns with this approach as well such as date ranges before the epoch but it is a very simplistic approach and might work depending on your needs.
const startDate = '10/10/2018';
const endDate = '03/09/2019';
const start = (new Date(startDate)).valueOf();
const end = (new Date(endDate)).valueOf();
const timeBetween = end - start;
console.log({timeBetween, days: Math.floor(timeBetween/86400000)});
A slightly more robust is to essentially use a counter that increments itself by adding 1 day to the counter and the start date while the start date is less than the end date. Again, there are some concerns with this approach but that also depends on your needs.
const startDate = '10/10/2018';
const endDate = '03/09/2019';
let start = new Date(startDate);
const end = (new Date(endDate)).valueOf();
let daysBetween = 0;
while (start.valueOf() < end) {
daysBetween++;
start.setDate(start.getDate() + 1);
}
console.log(daysBetween);
Finally, a more robust solution to avoid the variety of issues with manipulating and working with dates is to use a library like momentjs. Using its difference method would look like the following.
const start = moment([2018, 10, 10]);
const end = moment([2019, 3, 9]);
console.log(end.diff(start, 'days'));
<script src="http://momentjs.com/downloads/moment.min.js"></script>
Using the following code worked for me. I added 1 extra month to my end date and it gives the proper date range. Also, instead of Math.ceil, i used Math.round and it gives the right number of date.
function getDateArray (start, end) {
var arr = [];
var startDate = new Date(start);
var endDate = new Date(end);
endDate.setMonth( endDate.getMonth());
while (startDate <= endDate) {
arr.push(new Date(startDate));
startDate.setMonth(startDate.getMonth() + 1);
}
return arr;
}

Sum of to times using javascript

can anyone tell me how to do sum of two time using javascript (momentjs) for exemple the sum of:
2:44:56 and 2:50:56
i tried that but doesnt work:
2:44:56 + 2:50:56
any suggestions please??
Momentjs has a duration object that can be used to add or subtract two or more timespans.
const a = moment.duration('02:44:56');
const b = moment.duration('02:50:56');
const c = a.add(b);
console.log(c.hours() );
console.log(c.minutes() );
console.log(c.seconds() );
One could add the seconds, then calculate the carry value and add that to the sum of minutes and so on. That can be easily done with reduce:
function sum(date1, date2){
date1 = date1.split(":");
date2 = date2.split(":");
const result = [];
date1.reduceRight((carry,num, index) => {
const max = [24,60,60][index];
const add = +date2[index];
result.unshift( (+num+add+carry) % max );
return Math.floor( (+num + add + carry) / max );
},0);
return result.join(":");
}
console.log(
sum("2:44:56" , "2:50:56" )
);
Try it
You can do it like this. Use add method on moment object and pass your data.
let x = moment({
hours:'2',
minutes:'44',
seconds:'56'})
.add({
hours:'2',
minutes:'50',
seconds:'56' })
console.log(x)
or dynamically pass data
let time = {
hours: 2,
minutes:44,
seconds: 56
}
let time2 = {
hours: 2,
minutes:50,
seconds: 56
}
let y = moment(time)
.add(time2)
console.log(y)
The code:
var t1 = moment('2:44:56', 'HH:mm:ss');
var t2 = '2:50:56';
var parsed_t2 = t2.split(':') // [2, 50, 56]
var r = t1.add({
hours: parsed_t2[0], // 2
minutes: parsed_t2[1], // 50
seconds: parsed_t2[2], // 56
});
The process:
Parse the string as a moment object (helping it with defining the format we're using;
Split the time we want to add to the t1 by using the split() function effectively splitting our t2 into an array where we have [hours, minutes, seconds]
Add the the times together using the moments add() method.
Working example
moment() function takes hours, minutes, seconds as arguments and return a moment object which has a add() method that also can take hours, minutes, seconds as arguments and return total times.
Try addTimes(time1, time2)
function addTimes(time1, time2) {
let [hours1, minutes1, seconds1] = time1.split(':');
let [hours2, minutes2, seconds2] = time2.split(':');
return moment({ hours: hours1, minutes: minutes1, seconds: seconds1 })
.add({ hours: hours2, minutes: minutes2, seconds: seconds2 })
.format('h:mm:ss');
}
console.log(addTimes('2:44:56', '2:50:56'));
Good old JS solution:
var base = new Date(0);
var t1 = new Date(base);
var t2 = new Date(base);
t1.setUTCHours(2,45,50);
t2.setUTCHours(2,50,50);
var t = new Date(t1.getTime() + t2.getTime() - base.getTime());
result = t.getUTCHours() + ":" + t.getUTCMinutes() +":" + t.getUTCSeconds();
console.log(result);
Note that JS automatically converts time of the day to GMT timezone hence we need to use UTC version of time functions.

HOW do I creating an array of dates between a start and end date?

I want to create a list of dates starting from 2014/0/1 to 2020/11/31 (dates are represented in JavaScript).
This is the code
var initialTime = new Date(2014, 0, 1);
var endTime = new Date( 2050, 11, 31);
var arrTime = [];
arrTime.push(initialTime);
if( initialTime < endTime) {
for( var q = initialTime; q <= endTime; q.setDate(q.getDate() + 1)) {
arrTime.push(q);
}
}
document.querySelector("#Time").innerHTML = arrTime;
This is what the code returns. It is just a list of " Sun Jan 01 2051 00:00:00 GMT-0500 (EST)." How do I correct this?
When you do q.setTime( ... ) you are modifying the Date object itself. You are pushing the same object into the array at each iteration, hence modifying it modifies the entire array.
If you only want the string representations of the dates only, you can do:
let initialTime = new Date("2018-03-09Z08:00:00")
,endTime = new Date("2018-03-14Z08:00:00")
,arrTime = []
;
for (let q = initialTime; q <= endTime; q.setDate(q.getDate() + 1)) {
arrTime.push(q.toString());
}
console.log(arrTime);
Or, if you want to have an array of actual Date instances:
let initialTime = new Date("2018-03-09Z08:00:00")
,endTime = new Date("2018-03-14Z08:00:00")
,arrTime = []
,dayMillisec = 24 * 60 * 60 * 1000
;
for (let q = initialTime; q <= endTime; q = new Date(q.getTime() + dayMillisec)) {
arrTime.push(q);
}
console.log(arrTime);
first of all you can not compare two dates using ==
second problem is you need to create a new Date object each time you push one to the array ex. .push(new Date(q.getTime())
the next problem is you aren't properly adding a day to the last day each time before you push into the array
do something like
pseudo code ---
var dates = [];
while( firstDate < secondDate ){
// this line modifies the original firstDate reference which you want to make the while loop work
firstDate.setDate(firstDate.getDate() + 1);
// this pushes a new date , if you were to push firstDate then you will keep updating every item in the array
dates.push(new Date(firstDate);
}
You are pushing the same memory reference to the array, hence the changes you make affect all of them.
Try:
var copiedDate = new Date(q.getTime());
arrTime.push(copiedDate);
This way you are always pushing a new object.
var resolution = 1000, // Number of dates to capture between start and end
results = [], // will be populated with the for loop
start = Date.now(), // Set to whatever you want
end = start + (1000 * 60 * 60 * 24), // Set to what ever you want
delta = end - start
for (let i = 0; i < resolution; i++) {
let t = (delta / resolution) * i
results.push(new Date(start + t))
}
console.log(results)
live example: https://jsfiddle.net/5ju7ak75/1/
Short ES6 solution:
const getDatesInRange = (min, max) => Array((max-min)/86400000).fill(0).map((_, i) => new Date((new Date()).setDate(min.getDate() + i)))
Example
getDatesInRange(new Date('12-25-2000'), new Date('12-25-2001'))

Loop through a date range with JavaScript

Given two Date() objects, where one is less than the other, how do I loop every day between the dates?
for(loopDate = startDate; loopDate < endDate; loopDate += 1)
{
}
Would this sort of loop work? But how can I add one day to the loop counter?
Thanks!
Here's a way to do it by making use of the way adding one day causes the date to roll over to the next month if necessary, and without messing around with milliseconds. Daylight savings aren't an issue either.
var now = new Date();
var daysOfYear = [];
for (var d = new Date(2012, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
daysOfYear.push(new Date(d));
}
Note that if you want to store the date, you'll need to make a new one (as above with new Date(d)), or else you'll end up with every stored date being the final value of d in the loop.
Based on Tom GullenĀ“s answer.
var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var loop = new Date(start);
while(loop <= end){
alert(loop);
var newDate = loop.setDate(loop.getDate() + 1);
loop = new Date(newDate);
}
I think I found an even simpler answer, if you allow yourself to use Moment.js:
// cycle through last five days, today included
// you could also cycle through any dates you want, mostly for
// making this snippet not time aware
const currentMoment = moment().subtract(4, 'days');
const endMoment = moment().add(1, 'days');
while (currentMoment.isBefore(endMoment, 'day')) {
console.log(`Loop at ${currentMoment.format('YYYY-MM-DD')}`);
currentMoment.add(1, 'days');
}
<script src="https://cdn.jsdelivr.net/npm/moment#2/moment.min.js"></script>
If startDate and endDate are indeed date objects you could convert them to number of milliseconds since midnight Jan 1, 1970, like this:
var startTime = startDate.getTime(), endTime = endDate.getTime();
Then you could loop from one to another incrementing loopTime by 86400000 (1000*60*60*24) - number of milliseconds in one day:
for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
{
var loopDay=new Date(loopTime)
//use loopDay as you wish
}
Here simple working code, worked for me
var from = new Date(2012,0,1);
var to = new Date(2012,1,20);
// loop for every day
for (var day = from; day <= to; day.setDate(day.getDate() + 1)) {
// your day is here
console.log(day)
}
var start = new Date("2014-05-01"); //yyyy-mm-dd
var end = new Date("2014-05-05"); //yyyy-mm-dd
while(start <= end){
var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1);
var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate());
var yyyy = start.getFullYear();
var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd
alert(date);
start = new Date(start.setDate(start.getDate() + 1)); //date increase by 1
}
As a function,
function getDatesFromDateRange(from, to) {
const dates = [];
for (let date = from; date <= to; date.setDate(date.getDate() + 1)) {
const cloned = new Date(date.valueOf());
dates.push(cloned);
}
return dates;
}
const start = new Date(2019, 11, 31);
const end = new Date(2020, 1, 1);
const datesArray = getDatesFromDateRange(start, end);
console.dir(datesArray);
Based on Tabare's Answer,
I had to add one more day at the end, since the cycle is cut before
var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var newend = end.setDate(end.getDate()+1);
var end = new Date(newend);
while(start < end){
alert(start);
var newDate = start.setDate(start.getDate() + 1);
start = new Date(newDate);
}
Didn't want to store the result in an array, so maybe using yield?
/**
* #param {object} params
* #param {Date} params.from
* #param {Date} params.to
* #param {number | undefined} params.incrementBy
* #yields {Date}
*/
function* iterateDate(params) {
const increaseBy = Math.abs(params.incrementBy ?? 1);
for(let current = params.from; current.getTime() <= params.to.getTime(); current.setDate(current.getDate() + increaseBy)) {
yield new Date(current);
}
}
for (const d of iterateDate({from: new Date(2021,0,1), to: new Date(2021,0,31), incrementBy: 1})) {
console.log(d.toISOString());
}
If you want an efficient way with milliseconds:
var daysOfYear = [];
for (var d = begin; d <= end; d = d + 86400000) {
daysOfYear.push(new Date(d));
}
Let us assume you got the start date and end date from the UI and stored it in the scope variable in the controller.
Then declare an array which will get reset on every function call so that on the next call for the function the new data can be stored.
var dayLabel = [];
Remember to use new Date(your starting variable) because if you dont use the new date and directly assign it to variable the setDate function will change the origional variable value in each iteration`
for (var d = new Date($scope.startDate); d <= $scope.endDate; d.setDate(d.getDate() + 1)) {
dayLabel.push(new Date(d));
}
Based on Jayarjo's answer:
var loopDate = new Date();
loopDate.setTime(datFrom.valueOf());
while (loopDate.valueOf() < datTo.valueOf() + 86400000) {
alert(loopDay);
loopDate.setTime(loopDate.valueOf() + 86400000);
}

Categories