How to add new minutes value for every next array element? - javascript

I want to add 36 minutes for every next value in the array but I get only one increase for all elements in array how to implement an algorithm which I describe above
let timestamps = [
"2020-01-21T22:36:00.000Z",
"2020-01-21T23:12:00.000Z",
"2020-01-21T23:48:00.000Z",
"2020-01-22T00:24:00.000Z",
"2020-01-22T01:00:00.000Z",
]
const minutesToAdjust = 36
const millisecondsPerMinute = 60000
const oneDay = 1000 * 60 * 60 * 24
const twentyFourHours = new Date(new Date() - oneDay)
const transformTimeseriesTo24h = timestamps.map(el => {
el = new Date(twentyFourHours + (minutesToAdjust * millisecondsPerMinute))
return el
})
timestamps = transformTimeseriesTo24h
console.log(timestamps)

Using Date.parse(el)
let timestamps = [
"2020-01-21T22:36:00.000Z",
"2020-01-21T23:12:00.000Z",
"2020-01-21T23:48:00.000Z",
"2020-01-22T00:24:00.000Z",
"2020-01-22T01:00:00.000Z",
]
const minutesToAdjust = 36
const millisecondsPerMinute = 60000
const oneDay = 1000 * 60 * 60 * 24
const twentyFourHours = new Date(new Date() - oneDay)
const transformTimeseriesTo24h = timestamps.map(el => {
return new Date(Date.parse(el) + (minutesToAdjust * millisecondsPerMinute))
})
timestamps = transformTimeseriesTo24h
console.log(timestamps)

Your code is ignoring the original dates by immediately assigning to el. Instead, since they're valid ISO-8601 date/time strings, parse them then add 36 minutes to them:
timestamps = timestamps.map(el => {
const dt = new Date(el);
dt.setMinutes(dt.getMinutes() + 36); // Will wrap for you
return dt; // Or `return dt.toISOString();`
});
Live Example:
let timestamps = [
"2020-01-21T22:36:00.000Z",
"2020-01-21T23:12:00.000Z",
"2020-01-21T23:48:00.000Z",
"2020-01-22T00:24:00.000Z",
"2020-01-22T01:00:00.000Z",
];
timestamps = timestamps.map(el => {
const dt = new Date(el);
dt.setMinutes(dt.getMinutes() + 36); // Will wrap for you
return dt; // Or `return dt.toISOString();`
});
console.log(timestamps);
Or... "Every next value" sounds like you want to add 0 to the first one, 36 minutes to the second one, 72 (36 * 2) minutes to the third, ...? If so, you can use the index that map passes as the second argument:
timestamps = timestamps.map((el, index) => {
const dt = new Date(el);
dt.setMinutes(dt.getMinutes() + (index * 36)); // Will wrap for you
return dt; // Or `return dt.toISOString();`
});
Live Example:
let timestamps = [
"2020-01-21T22:36:00.000Z",
"2020-01-21T23:12:00.000Z",
"2020-01-21T23:48:00.000Z",
"2020-01-22T00:24:00.000Z",
"2020-01-22T01:00:00.000Z",
];
timestamps = timestamps.map((el, index) => {
const dt = new Date(el);
dt.setMinutes(dt.getMinutes() + (index * 36)); // Will wrap for you
return dt; // Or `return dt.toISOString();`
});
console.log(timestamps);
I couldn't tell whether you wanted to end up with Date instances of ISO strings. The above result in Date instances. If you want ISO strings instead, just call toISOString() on dt when returning it (see comments above).

You need to use timestamp value from array and add your offset in that
let timestamps = [
"2020-01-21T22:36:00.000Z",
"2020-01-21T23:12:00.000Z",
"2020-01-21T23:48:00.000Z",
"2020-01-22T00:24:00.000Z",
"2020-01-22T01:00:00.000Z",
];
const minutesToAdjust = 36
const millisecondsPerMinute = 60000
const oneDay = 1000 * 60 * 60 * 24
const twentyFourHours = new Date(new Date() - oneDay)
timestamps = timestamps.map(time => new Date(new Date(time).getTime() + minutesToAdjust * millisecondsPerMinute));
console.log(timestamps)

I would convert your time stamps to Unix time add the 36*60 seconds to it, and convert it back to your format.

Related

I want to add 15 minutes slot to each StartTime in a loop and store in array of objects

const createTimeSlots=(fromTime,toTime)=>{
I want to add 15 minutes slot to each StartTime in a loop and store in array of objects.
Assuming the inputs are in timestamp, add 15 mins equivalent of timestamps and push that timestamp(or push mins/hrs etc.). Here's the code example where start time is current timestamp and endtime is current + 3hrs in timestamp.
function createSlots(start, end) {
let slots = [];
const mins = 15 * 60 * 1000; // 15 mins
const date = (dt) => new Date(dt);
while (start <= end) {
start += mins;
// only mins
//slots.push(date(start).getMinutes());
// hrs + mins
slots.push(`${date(start).getHours()}:${date(start).getMinutes()}`);
}
return slots;
}
var slots = createSlots(Date.now(), Date.now() + 3 * 3600 * 1000); // from (now) to (now + 3hrs)
console.log("slots : ", slots);
Let's assume inputs are valid date-time format.
This solution will work across dates, let's say you give the start time today and end time tomorrow then also it will work without any issue.
const createTimeSlots = (fromTime, toTime, slotLength =15*60) => {
let slotStart = new Date(fromTime).valueOf();
let slotEnd = new Date(fromTime).valueOf() + slotLength * 1000;
let endEpoch = new Date(toTime).valueOf();
let ob = [];
for (slotEnd; slotEnd <= endEpoch; slotEnd = slotEnd + slotLength * 1000) {
ob.push({
'from': formatDate(slotStart),
'to': formatDate(slotEnd)
});
slotStart = slotEnd;
}
return ob;
}
function formatDate(epoch) {
let d = new Date(epoch);
let month = String((d.getMonth() + 1)).padStart(2, '0');
let day = String((d.getDate())).padStart(2, '0');
let hours = String((d.getHours())).padStart(2, '0');
let mins = String((d.getMinutes())).padStart(2, '0');
return `${d.getFullYear()}-${month}-${day} ${hours}:${mins}`;
}
const from = "2022-05-25 23:00";
const to = "2022-05-26 01:00";
const slotLength = 15 * 60; //seconds
var r = createTimeSlots(from, to, slotLength );
console.log(r);

Convert string to time and add 2 hours in JS

i get this time from an external JSON :
"time":"19:45"
I need to add 2 hours from this string.
Is it possible in JS?
Thanks
Try this
let myTime = '19:45'
function getTime(time, addHour) {
let [h, m] = time.split(':');
let date = new Date();
date.setHours(h, m, 0)
date.toString();
let res = `${date.getHours()+addHour}:${date.getMinutes()}`
return res
}
console.log(getTime( myTime, 2 ))
uses String.split to get hourNum and minuteNum, then construct one Date object and uses setTime to add two hours.
function addHours(text, hours=2) {
const [hourNum, minNum] = text.split(':')
const time = new Date(0, 0, 0, hourNum, minNum)
time.setTime(time.getTime() + (hours * 60 * 60 * 1000))
return `${time.getHours()}:${time.getMinutes()}`
}
console.log(addHours('19:45', 2))
console.log(addHours('23:45', 2))
A Date object isn't necessary to do time mathematics, it just means taking account of minutes and seconds (60) and maybe days (24).
E.g.
// Add time to a timestamp, both in in HH:mm format
// If respectDay is true, hours are % 24
function addTime(start, increment, respectDay = false) {
let pad = n => ('0' + n).slice(-2);
let timeToMins = time => time.split(':').reduce((h, m) => h*60 + m*1);
let minsToTime = (mins, respectDay = false) => `${pad((mins / 60 | 0) % (respectDay? 24 : Number.POSITIVE_INFINITY))}:${pad(mins%60)}`;
return minsToTime(timeToMins(start) + timeToMins(increment), respectDay);
}
let time = "19:45";
console.log(addTime(time, '8:23')); // Total time : 28:08
console.log(addTime(time, '8:23', true)); // As day time : 04:08

Calculate duration by start and end hour

I have this json :
{
endTime: "14:00:00"
startTime: "12:00:00"
}
I need to calculate duration, so I did like this :
let duration = endTime.slice(0, -3) - startTime.slice(0, -3);
But not working as expected. I have a js error : left-hand must be type number
Have an idea about that ?
Thx in advance.
Ok, I'm considering you are only receiving an object with endTime and startTime properties and not working with arrays.
In the following code block, you can transform your strings into dates and do calcs with them. In this example, I just subtracted endDate - startDate to get the difference in milliseconds and then I converted to seconds, minutes and hours.
const data = {
endTime: '14:00:00',
startTime: '12:00:00',
}
// separates the string in hours, minutes and seconds
const [startHours, startMinutes, startSeconds] = data.startTime.split(':')
const [endHours, endMinutes, endSeconds] = data.endTime.split(':')
// creates a Date instance to work with
const startDate = new Date()
const endDate = new Date()
// sets hour, minutes and seconds to startDate
startDate.setHours(startHours)
startDate.setMinutes(startMinutes)
startDate.setSeconds(startSeconds)
// sets hour, minutes and seconds to endDate
endDate.setHours(endHours)
endDate.setMinutes(endMinutes)
endDate.setSeconds(endSeconds)
const differenceInMilliseconds = endDate - startDate
const differenceInSeconds = differenceInMilliseconds / 1000
const differenceInMinutes = differenceInSeconds / 60
const differenceInHours = differenceInMinutes / 60
console.log(differenceInHours) // outputs 2 hours
Too many ways to do that, this is one of the simple ways.
Cast the time to a Date object, then get their timestamp (ms), finally get the duration:
const startTimeTs = new Date(`2021-04-01 ${startTime}`).valueOf();
const endTimeTs = new Date(`2021-04-01 ${endTime}`).valueOf();
const durationTs = endTimeTs - startTimeTs;
const durationInSecondes = durationTs / 1000;
const durationInMinutes = durationInSecondes / 60;
const durationInHours = durationInMinutes / 60;
const json = {
endTime: "14:00:00",
startTime: "12:00:00"
};
const start = new Date(2000, 3, 3, ...(json.startTime.split(':').map( x => Number(x))));
const end = new Date(2000, 3, 3, ...(json.endTime.split(':').map( x => Number(x))));
const output = document.getElementById('output');
output.textContent = ((end-start)*0.001)+ ' seconds difference';
<div id="output"></div>
There to many ways to do it, but if you need in same format as you got in json you can use something like it
const data = {
endTime: "14:00:00",
startTime: "12:00:00"
};
const { endTime, startTime } = data;
const endTimeArr = endTime.split(':').map(el => +el);
const startTimeArr = startTime.split(':').map(el => +el);
const resArr = endTimeArr.map((el, i) => el - startTimeArr[i]);
const res = resArr.join(':');
You can do it like this:
let times = {
endTime: "14:00",
startTime: "12:00:00"
};
function calculate(obj) {
let startTime = obj.startTime;
let endTime = obj.endTime;
let sum = new Date(parseInt(endTime)) - new Date(parseInt(startTime));
return sum;
}
console.log(calculate(times));
Convert the HH:MM:SS to seconds.
Subtract the two values - you get the seconds of duration.
Convert the seconds to HH:MM:SS.
/* helper functions */
const format = n =>
String(n).padStart(2, 0);
const time2seconds = time => {
const [hours, minutes, seconds] = time.split(":").map(Number);
return seconds + minutes * 60 + hours * 60 * 60;
}
const seconds2time = seconds => {
const hours = format(Math.floor(seconds / (60 * 60)));
const minutes = format(Math.floor(seconds / 60) % 60);
seconds = format(seconds % 60);
return `${hours}:${minutes}:${seconds}`;
}
/* /helper functions */
const toDuration = ({startTime, endTime}) =>
seconds2time(time2seconds(endTime) - time2seconds(startTime));
test({
endTime: "14:00:00",
startTime: "12:00:00"
})
test({
endTime: "15:30:00",
startTime: "11:00:00"
})
test({
endTime: "18:24:05",
startTime: "11:47:12"
})
function test(obj) {
const result = toDuration(obj);
console.log(`duration between ${obj.startTime} and ${obj.endTime} is: ${result}`);
}

How to sum time string in an array?

Suppose, I've an array of different time string.
let a: any = ["7:20", "5:50", "6:30"];
I want to sum up these HH:mm time strings. I am building up an app using Ionic 4 (Angular). I have already used momentjs for these. But, unfortunately yet I can't find any solution.
Update:
Expected Result:
7:20 + 5:50 + 6:30 = 19:40 (HH:33)
You can treat time as moment durations that can be summed up:
const any = ['7:20', '7:52', '5:03', '1:01', '9:02', '6:00'];
const sum = any.reduce((acc, time) => acc.add(moment.duration(time)), moment.duration());
console.log([Math.floor(sum.asHours()), sum.minutes()].join(':'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
You could use reduce method by passing a callback function.
let arr= ["7:20", "5:50", "6:30"];
toSeconds = (str) => {
str = str.split(':');
return (+str[0]) * 60 + (+str[1]);
}
toHHss = (seconds) => {
let minutes = parseInt(seconds/60);
seconds = seconds - minutes*60;
return minutes + ':' + seconds;
}
let result = arr.reduce((r,elem) => r + toSeconds(elem), 0);
console.log(toHHss(result));
A POJS solution can be very simple:
/* Add array of time strings in H:mm format
** #param {Array<string>} timeArray - Array of H:mm
** #returns {string} - sum of times in H:mm format
*/
function addTimes(timeArray) {
let mins = timeArray.reduce((acc, time) => {
let [h, m] = time.split(':');
acc += h*60 + m*1;
return acc;
}, 0);
return (mins/60|0) + ':' + ('0'+(mins%60)).slice(-2);
}
// Example
console.log(addTimes(["7:20", "5:03", "6:42"]));
Vanilla Javascript implementation:
const secondsToHm = s => ({
hours: ((s - s % 3600) / 3600) % 60,
minutes: ((s - s % 60) / 60) % 60,
})
let a = ["7:20", "5:50", "6:30"];
let total = 0;
for(let i = 0; i < a.length; i++){
const aSlice = a[i].split(':');
const aSeconds = (+aSlice[0]) * 60 * 60 + (+aSlice[1]) * 60;
total += aSeconds
}
console.log(`${secondsToHm(total).hours}:${secondsToHm(total).minutes}`);
You can use moment.duration() to get the number of milliseconds for each time string in the array, and add them.
a.reduce((acc, t) => acc.add(moment.duration(t)), moment.duration())

How to get the difference between two timestamps in JavaScript?

I have these two timestamps: "08:00" and "10:40", and i need to get the amount of minutes between these two, which in the case would be 160.
Can someone please help?
This is not exactly timestamps. But you can do it this way:
function getMinutesDelta(time1, time2) {
const [h1, m1] = time1.split(':');
const [h2, m2] = time2.split(':');
const ts1 = new Date().setHours(h1, m1);
const ts2 = new Date().setHours(h2, m2);
return Math.abs((ts2 - ts1) / (1000 * 60));
}

Categories