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);
Related
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);
I need to count the remaining time in hours between today or actual date/time and a specific end date at 00:00 hrs.
I tried in this fiddle, but I get the counting of one month more than it should be.
https://jsfiddle.net/alonsoct/52ts89mz/
var endTime = new Date(2019,10,18,0,0,0) / 1000;
function setClock() {
var elapsed = new Date() / 1000;
var totalTime = endTime - elapsed;
var hr = parseInt(totalTime / 3600)
var min = parseInt(totalTime / 60) % 60;
var sec = parseInt(totalTime % 60, 10);
var result = hr + " hours, " + min + " minutes " + sec + " seconds";
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
If I enter one month less in the "endTime" variable I get the correct result in hours count, but this is not fine I need to enter the real end date without the need to subtract one month.
Thanks
The code below is mostly your code with one change. I changed the input for endTime to an ISO format and omitted the time Zone. This, in theory, will default to your browser's timezone. I tested on your linked and it worked. Here is some additional information https://www.w3schools.com/js/js_date_formats.asp
var endTime = new Date("2019-10-18T00:00:00") / 1000;
function setClock() {
var elapsed = new Date() / 1000;
var totalSec = endTime - elapsed;
var h = parseInt( totalSec / 3600 )
var m = parseInt( totalSec / 60 ) % 60;
var s = parseInt(totalSec % 60, 10);
var result = h + " hours, " + m + " minutes " + s + " seconds";
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
Here is a working solution with Vanilla JS:
var calcTime = setInterval(function(){
date_future = new Date(2019,10,18,0,0,0)
date_now = new Date();
seconds = Math.floor((date_future - (date_now))/1000);
minutes = Math.floor(seconds/60);
hours = Math.floor(minutes/60);
days = Math.floor(hours/24);
hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);
It's pretty easier with JQuery → http://hilios.github.io/jQuery.countdown/examples/show-total-hours.html
JavaScript counts months from 0 to 11.
January is 0. December is 11.
I think you were thinking that endTime will be October 18th, 2019 but actually it's November 18th, 2019.
You can see more relevant information here.
https://www.w3schools.com/js/js_dates.asp
Thanks.
If between the start-datetime and end-datetime a change takes place in winter / summertime remember to make summertime/wintertime adjustments
(if you get these values from e.g. an api:) if the startdate is specified by a client in location x and enddate is specified in location y, you have take into account that the startdate could potentially be in 00:00:00+14:00 timezone and end the endate in max -14 timezone.
if you only present 2 timeboxes: time 1 and time 2, you can map these anywhere on a 52 hours time-scale: -14 , +14 and the 24 hours gmt timescale where you then would normalize to. ( 0:00 could mean i am in Samoa +14, 14 hours ahead of the end of GMT 23:59:59 (14 further) or ahead of GMT 0:00 (14+24 further). Then there are countries which make local time decisions e.g. in India with +5.5 UTC or Burma +6.5 or newfoundland -3.5.
Since this is stackexchange and people will copy and paste these examples in their applications even if these applications are "on the internet" and so DO have users from every location in the world.
Therefore ... use a library: https://momentjs.com/ ; Get hours difference between two dates in Moment Js they have a helper https://momentjs.com/docs/#/displaying/to/ and see also: Moment.js - How To Detect Daylight Savings Time And Add One Day
You can see the same bug on https://www.timeanddate.com/countdown but they added in words : https://www.timeanddate.com/countdown/one-hour-offwintertijd (and they assume the end datetime is in the same location as the countdown datetime)
I want to an "order withing x amount of hours for next day delivery". I'm guessing the best way would be JS? but I'm not good at it to pick apart and edit anything I've found so far
My problem is that all of the ones I find are set to specific dates such as June 5th 2018 12:00.
Basically I want it to be set to 17:00 and if it's 15:30, I wan't the timer to say "order withing 1 hours 30 minutes for next day delivery" and then start from 23 hours 59 minutes once the time hits 17:01.
Create a timestamp for arrival and a timestamp based upon the absolute distance to arrival, and use the latter for countdown:
//Order timestamps
var arrived = new Date();
arrived.setHours(15);
arrived.setMinutes(0);
arrived.setSeconds(0);
arrived.setTime(arrived.getTime() + 86400000);
//Drawing example
var arriveNode = document.body.appendChild(document.createElement("p"));
arriveNode.innerHTML = "Arrives in: ";
var arriveNodeTime = arriveNode.appendChild(document.createElement("b"));
setInterval(function() {
var d = new Date(Math.abs(Date.now() - arrived.getTime()));
arriveNodeTime.innerHTML = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}, 100);
This is an easy thing to do in PHP with code like this;
if (strtotime($given_time) >= time()+300) echo "You are online";
But can't find anything on SO to do exactly this in javascript.
I want to check if the difference between a given time and the current time is less than 45mins
For instance
$scope.given_time = "14:10:00"
$scope.current_time = new Date();
I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.
Then this should be true
How can I achieve this with Javascript:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Javascript uses unix timestamps in milliseconds, so it is similar to the output of strtotime (which uses seconds).
var date = new Date();
Then you'll need to do the calculation from milliseconds. (Minutes * 60 * 1000)
You can also use date.parse() to parse a string to milliseconds, just like strtotime() in PHP does to seconds.
In full:
var date = new Date();
var last = new Date('Previous Date'); // or a previous millisecond timestamp
if ( ( date - last ) > ( 45 * 60 * 1000 ) ) {
// do something
}
You could use a static date to compare just time, this is exactly what strtotime does if you exclude the date:
var last = new Date('1/1/70 14:10:00');
var date = new Date('1/1/70 14:30:00');
However, this approach will fail if you're trying to compare time that cross over day boundaries.
Try this:
function checkTime(time) {
var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
if (minutes > 45 || (minutes < 0 && minutes > -1395)) {
// greater than 45 is todays time is above 45 minutes
// less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
document.write(time + ': true<br />');
} else {
document.write(time + ': false<br />');
}
}
checkTime("14:10:00");
checkTime("16:30:00");
checkTime("17:10:00");
There's a JavaScript method called getMinutes(); you can use to get only the minutes and compare.
Your code should look something like:
var received_time = "14:10:00".split(':');
var minute = '';
if(received_time.length === 3) {
minute = parseInt(received_time[1], 10);
}
$scope.given_time = minute;
var the_time = new Date();
$scope.current_time = the_time.getMinutes();
And you now can do your thing:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Using a library like moment.js you can simply diff the two times.
var $log = $("#log");
/* Difference between just times */
$log.append("Difference between times\n");
var givenTime = moment("14:10:00", "HH:mm:ss");
var minutesPassed = moment("14:30:00", "HH:mm:ss").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
/* Better: Difference between times that have dates attached to them and cross a day boundary. */
$log.append("\n\nDifference between dates with times\n");
givenTime = moment("2015-12-03 23:33:00");
minutesPassed = moment("2015-12-04 00:14:00").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.js"></script>
<p>Results:</p>
<hr>
<pre id="log"></pre>
<hr>
Caveat: If the given time is yesterday such as 11:30pm and the current time is 12:10am then you will get the wrong result. You'd want to use a date with the time if this type of thing is an issue for your use case.
The moment.js documentation
http://momentjs.com/docs/
Angular directive for moment documentation
https://github.com/urish/angular-moment/blob/master/README.md
I'm using a mysql timestamp to calculate the difference of time through JavaScript as below,
function parseMySQLTimestamp(timestamp) {
var parts = timestamp.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);
return new Date(+parts[1], (+parts[2] - 1), +parts[3], +parts[4], +parts[5], +parts[6]);
}
var informTime = "2011-11-09 08:00:00";
var diff = (new Date()- parseMySQLTimestamp(informTime));
var months = Math.floor(diff /(60*60*24*30*1000));
diff=Math.abs(diff-(months*60*60*24*30*1000));
var days = Math.floor(diff/(60 * 60 * 24*1000));
diff=Math.abs(diff-(days*60*60*24*1000));
var hour=Math.floor(diff/(60*60*1000));
diff=Math.abs(diff-(hour*60*60*1000));
var minute=Math.floor(diff/(60*1000));
var message=months +" months "+ days + " D " + hour + " Hr " + minute + "min ago ";
alert(message);
it will give the correct result but I'm afraid that it will not be correct in the months which have 31,28 or 29 days other wise in leap years.
How to achieve reliable functionality? I feel it's so complicated. Thank you.