How to add some minutes to a Date format - javascript

So I'm working with the Google Calendar API and because the required date format I´m using the next way to get the starting time:
const date1 = (mail._doc.Data[1].Date + 'T' + mail._doc.Data[1].Time )
const startingTime = new Date (date1)
This works and give me the next input that allows me to create the event in the calendar if I manually set the ending time
2022-07-15T21:23:00.000Z
That starting time will change depending of data in the server. For the ending time I would like for it to be the starting time (whatever it is) plus 45 minutes but I cant make it work.

You can use timestamp in getTime() and use this formula to extend the current timestamp
45 minutes x 60 seconds x 1000 miliseconds
const startTime = new Date() //your starting time
console.log(startTime)
const startTimestamp = startTime.getTime()
//45 minutes x 60 seconds x 1000 miliseconds
const timeExtent = 45*60*1000
const endTime = new Date(startTimestamp + timeExtent)
console.log(endTime)

const date = new Date();
console.log('Before : ' + date);
date.setMinutes(date.getMinutes() + 45); //adding 45 minutes
console.log('After : ' + date);

Related

set hours and get ms with Date in js

how can I get the ms of the day at midnight with vanilla js ; something like this:
const today = new Date().setHours(0,0,0,0)
return today.getTime()
And as well how can i get the ms of just the current hours and minutes . Something like
const hours = new Date().gethours()
const minutes = new Date().getminutes()
const now = (hours + minutes) in millisecond
thanks
how can I get the ms of the day at midnight with vanilla js ; something like this:
const today = new Date().setHours(0,0,0,0)
return today.getTime()
You're close, but don't use the return value of setHours, use the date object:
const today = new Date();
today.setHours(0,0,0,0);
return today.getTime();
That's working in local time. If you want UTC, use setUTCHours instead.
And as well how can i get the ms of just the current hours and minutes . Something like
const hours = new Date().gethours()
const minutes = new Date().getminutes()
const now = (hours + minutes) in millisecond
The methods are getHours and getMinutes (capitalization matters). If you're trying to get "milliseconds since midnight", it would be:
const dt = new Date();
const msSinceMidnight = ((dt.getHours() * 60) + dt.getMinutes()) * 60 * 1000;
return msSinceMidnight;
...since there are 60 minutes in an hour, 60 seconds in a minute, and 1000ms in a second. (Note that you haven't used getSeconds there, so seconds will be ignored.)
setHours returns the time value of the updated Date, so for the local midnight time value:
let today = new Date().setHours(0,0,0,0);
does the job. If you want local milliseconds since midnight, then:
let msSinceMidnight = new Date() - new Date().setHours(0,0,0,0);
Getting UTC milliseconds since midnight is simpler, as in ECMAScript UTC days are always 8.64e7 ms long:
let msSinceUTCMidnight = new Date() % 8.64e7;
let today = new Date().setHours(0,0,0,0);
console.log(`today: ${today}`);
let msSinceMidnight = new Date() - new Date().setHours(0,0,0,0);
console.log(`msSinceMidnight: ${msSinceMidnight}`);
let msSinceUTCMidnight = new Date() % 8.64e7;
console.log(`msSinceUTCMidnight: ${msSinceUTCMidnight}`);

Calculating sleep time on a 24-hour clock

I'll start by saying that i'm a beginner with HTML, Javascript and so on.
I'm building an alarm clock and now trying to add a feature that calculates the time you have to sleep.
I'm using a 24-hour clock format, and at the moment I have these parameters:
let tempWakeUpHour; //stores the 'hours' value that the user chooses in a 00 format. (01 means 01:00, 02 means 02:00, and so on, 23 means 23:00 and 24 means midnight).
let tempWakeUpMin; //stores the 'minutes' value that the user chooses in a 00 format and has only the options of 00, 05, 10, 15, and up to 55.
So the user can choose an 'hour' to wake up (24 options), and 'minutes' (12 options).
The problem i'm having is with calculating the time the user has to sleep from the time 'now' :
let dateNow = new Date();
let hourNow = dateNow.getHours();
let minNow = dateNow.getMinutes();
let tempSleepHours; **// should calculate the hours left to sleep.**
let tempSleepMins; **// should calculate the minutes left to sleep.**
...innerHTML = "you have " + tempSleepHours + " hours and " + tempSleepMins + " minutes to sleep.";
At first I tried
let tempSleepHours = Math.abs(tempWakeUpHour - hourNow);
let tempSleepMins = Math.abs(tempWakeUpMin - minNow);
but that doesn't cover all the options.
I'd appreciate it if anyone has the solution for this.
Thanks!
You need to take into account that the wakeup time will likely be in the morning and the current time could be in the evening, so hours wouldn't be a straightforward calculation (though still doable). What you could do is convert the wakeup time into a date and do a simple date comparison. For example:
let wakeupat = new Date();
wakeupat.setHours(32);
wakeupat.setMinutes(0);
wakeupat.setSeconds(0);
wakeupat.setMilliseconds(0);
function sleepremaining() {
let now = new Date();
let diff = wakeupat - now;
if (diff < 0) {
console.log("Wake up!!!!");
clearInterval(timer);
} else {
let remaining = new Date(diff);
console.log(remaining.getHours() + " hours " + remaining.getMinutes() + " minutes and " + remaining.getSeconds() + " seconds");
}
}
let timer = setInterval(sleepremaining, 1000);

Formatting seconds duration into DD:HH:mm format by using moment.js

I'm trying to count calculate a duration from seconds into a DD-HH-mm format.
My javascript code:
var seconds = 120;
var result = moment.utc(seconds*1000).format('DD:HH:mm');
My code should return something like this: 00:00:02 (DD:HH:MM) but it returns that: 01:00:02 (DD:HH:MM)!
I'm sure that's because of my local time, but how to fix the 1 hour interval in general?
moment.utc creates a moment.js object with a timezone set to GMT/UTC. When using a date for a duration, you need to allow for the date starting from 1, not zero. Also, if the duration is 32 days or longer, the "days" will reset to 1.
Moment.js also has durations, however, they don't support formatting other than "humanize" or converting to particular units.
If your durations are less than 32 days, you can use a date starting from 1 January in any year provided you deal with the day number not being zero indexed (i.e. subtract 1 from the day).
So getting your required format with moment.js is a bit more work than just formatting a date, you'll need a sequence of steps so consider writing a function. A plain JS function is no more work than a moment one in this case, it will handle durations 32 days or longer and is not affected by Date vagaries like daylight saving and timezones.
var secs = 120;
// Using a duration
var m = moment.duration(secs * 1000);
console.log(m);
console.log(m.humanize());
console.log(m.asMinutes());
// Using a date and seconds value
var x = moment.utc(secs*1000);
// Generated date
console.log(x.format());
// Get the days separately
var dayNum = x.format('D') - 1;
// Format with hours and minutes
console.log(('0'+dayNum).slice(-2) + x.format(':HH:mm'))
// Function using moment.js
function myFormat(secs) {
var x = moment.utc(secs*1000);
var dayNum = x.format('D') - 1;
return ('0'+dayNum).slice(-2) + x.format(':HH:mm');
}
// Function without using a Date
function duration(secs) {
function z(n){return ('0'+n).slice(-2)}
return z((secs/8.64e4|0))
+ ':' + z((secs%8.64e4)/3.6e3|0)
+ ':' + z((secs%3.6e3)/60|0)
// + ':' + z(secs%60);
}
console.log(duration(secs));
// Some other tests
var min = 60;
var hr = 60*min; // 3,600
var day = 24*hr; // 86,400
//2 days 17 hours 53 minutes and 08 seconds
var d = 2*day + 17*hr + 53*min + 8;
//0 days 1 hour 2 minutes and 1 second
var e = 0*day + 1*hr + 2*min + 1;
// 48 days 21 hours 15 minutes
var f = 48*day + 21*hr + 15*min;
[120, d, e, f].forEach(function(d) {
console.log(d + ' seconds');
console.log('Plain js: ' + duration(d));
console.log('Moment fn: ' + myFormat(d));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
The format seems ambiguous, I think many would interpret it as HH:mm:ss rather than DD:HH:mm.

subtract time between two values set in localstorage

I have a quiz program written in vanilla JS. It is supposed to log the time it takes to complete it.
What I would like to achieve is how long it takes for the user to answer the questions by subtraction two variables (strings). If it is even possible.
When the user has stated his name and presses a button "STart Quiz" the currrent time is logged in localstorage like so:
var storeName;
var d = new Date();
var h = getHours();
var m = getMinutes();
var s = getSeconds();
var startTime = h + ":" + m + ":" + s;
var endTime = h + ":" + m + ":" + s;
var result;
var storage = {
storeName: storeName,
startTime: startTime,
endTime: null,
result: result
};
The tricky part is I do not know how to subtract startTime from EndTime to get the time it took to answer the questions. This quiz is over in minutes, so to use the hour is redundant.
When the user has clicked "submit" answer on the last question I want the time logged in LS as endTime.
I hope I have not been unclear and thank you all in advance very much for your time. Thank you.
Instead of storing string as date, directly store the time in milliseconds. Then you can subtract the start time with end time to figure out the time difference.
var startTime = Date.now();
var storage = {
storeName: storeName,
startTime: startTime,
endTime: null,
result: result
};
Later you can calculate the endTime using Date.now() and subtract that from startTime to get the time difference.
storage.endTime = Date.now();
//difference
var diff = storage.endTime - storage.startTime;
You use your new Date() wrong.
Should be this.
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
console.log(h);
As for futher implementation you should save current time then use timer on click/login. After that substract these two values. Example for seconds. You just devide (and/or take a modulo to go to real minutes at current time) by for example 3600 to get seconds instead of an hour. Or you can use all your variable and subtract the time. On the way if you get problems with addition for example you can get 5 + 3 = 53 instead of 8 you use Number(5) + Number(3) to do adition instead of concat. Good luck :P
EDIT: also to get time from your string. With split you get array of value.
var test = h + ":" + m + ":" + s;
console.log(test.split(":"));

Get the correct local time

I need to get the local time. I created this script but, for example, in italy ( where I live ), the alert shows 7 instead of 9. Why ?
var time = new Date().getTime();
var seconds = time / 1000;
seconds = seconds % 86400;
hours = parseInt(seconds / 3600);
alert(hours);
Because getTime returns the timestamp in milliseconds. And the timestamp is timezone independent. Use getTimezoneOffset() to get the offset in minutes from UTC, and add it.
new Date().getHours() will give you the local time, no adjustment needed.
new Date().getTimezoneOffset() will give you the number of minutes from UTC in the users's locale, should you need to offset an absolute time.
Note that UNIX timestamps measure the number of seconds since the UNIX epoch as if every day was exactly 3600 * 24 seconds. That allows you to get the time on most days with divisions and modulos, but if your timestamp is earlier than the latest leap second, and you try to do some simple maths with it, the result will not be accurate.
DEMO : http://jsfiddle.net/yk3wkcr8/
var currentTime = new Date();
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
alert(h);
alert(m);
alert(s);
If you want an example, try this: Fiddle
It uses full array with seconds, minutes, hours, date, day and year.
BTW you can use getHours(); followed by the others.
var d = new Date(),
hours = d.getHours(),
hour = (hours - 12),
year = d.getFullYear(),
second = d.getSeconds(),
minute = d.getMinutes();
alert (hour + ":" + minute + ":" + second);
etc, etc.
You can try this:
new Date().toLocaleString()
it will give you something like:
"4/16/2015, 9:14:53 AM"
And if you need to obtain only the time stamp then you can split the resulting string into an array and get the second item from the array:
new Date().toLocaleString().split(',')[1]
If you need only the hours this is the way:
new Date().getHours()

Categories

Resources