Calculating the time difference in javascript - javascript

I want to create a time differance calculator between two given time and a date number.
Also I want to tell you that I have made 4 input fields: time1, time2, days and timediff.
The time format that I want is very simple, ex: 700 for 7:00, 932 for 9:32, 1650 for 16:50 and so on...
Now I also have the day input field, where I can put in some numbers, ex: 1(for the first day, 2 for the second day and so on).
I want that if I put 1(first day) to not calculate the days, only to calculate the timediff, because it's the same day. But if I put 2 on the date field then 24hours(one day) to be added to the timediff, if I put 3 48hours(two days) to be added and so on...
I have something like this, but is not working well, when I change the day the result is mess up...
var time1 = document.getElementById('indulas').value;
var time2 = document.getElementById('erkezes').value;
var day = document.getElementById('nap').value;
if (day > "1"){ day * 2400 };
var time = (time2 * day) - time1;
document.getElementById('ido').value = time;

This cannot be solved as subtraction of two times in format HHMM because hour has only 60 minutes (eg. 900 - 732 = 168 does not equal to the correct 1 hour and 28 minutes)
This script should work
function pad(num, size) { // num = number which gets the leading zeros; size = number of digits the string will have (in your case 2)
var s = num.toString(); // convert integer to string
while (s.length < size) s = "0" + s; // if number of digits is smaller than requested, add leading zeros
return s; // return the number (as string) with leading zeros
}
var time1 = document.getElementById('indulas').value.match(/.{2}/g),
// split string each 2 characters ("0932" -> ["09", "32"])
time2 = document.getElementById('erkezes').value.match(/.{2}/g),
// day 1 is today, day 2 - 1 adds 24 hours
days = parseInt(document.getElementById('nap').value)-1,
// start date on day 0 at HH, MM
startDate = new Date(0, 0, 0, parseInt(time1[0]), parseInt(time1[1])),
// end date on day 0 + days at HH, MM
endDate = new Date(0, 0, days, parseInt(time2[0]), parseInt(time2[1])),
// subtract dates in milliseconds
diff = endDate.getTime() - startDate.getTime(),
// hour and minute in miliseconds
hour_in_mili= 1000 * 60 * 60,
minute_in_mili = 1000 * 60,
// calculate number of hours in diff time
hours = Math.floor(diff / hour_in_mili),
// calculate number of minutes in the diff time what left after subtracting the hours
minutes = Math.floor((diff - (hours * hour_in_mili)) / minute_in_mili);
/*
if indulas.value = "0932", erkezes.value = "1650", nap.value = "1"
script shows "7:18"
*/
document.getElementById('ido').value = hours + ":" + pad(minutes, 2);

Related

How to get 24:XX time from datetime?

Is there a DateTime Format that allows representation of the 24-hour clock to roll over where 24:XX is valid time?
For example
const secondsToTimeOfDay = (totalSeconds: number): string => {
return new Date(totalSeconds * 1000).toISOString().substr(11, 8);
};
var x = secondsToTimeOfDay(86399)
console.log(x)
Returns
23:59:59
But when seconds are greater than 86400 (The number of seconds in one day) it starts on the next day?
Example
var x = secondsToTimeOfDay(87000)
console.log(x)
Returns
00:10:00
Is there a date format that will return in a 24:xx format?
Example (I know this works but I want to know if it can be done using some kind of built-in Date Object)
const SomeNewFunction = (totalSeconds: number): string => {
var duration = 1000*totalSeconds
var milliseconds = parseInt((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)));
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
var x = SomeNewFunction(87000)
var y = SomeNewFunction(97000)
console.log(x)
console.log(y)
Returns
24:10:00
26:56:40
Where the SomeNewFuntion uses some kind of DateTimeObject rather than math?
The JavaScript Date object represents a single instant in the history of the world, both date and time. While you can ignore the date part in display, it is always there - new Date(300000) doesn't represent "00:05:00 on any day", it represents "00:05:00 on January 1st 1970, according to UTC".
Since January 1st 1970 didn't have a 25th and 26th hour, the format you're asking for wouldn't make sense. Put a different way, "Feb 2nd 02:00" and "Feb 1st 26:00" are the same instant in time, but (if I understand your problem correctly) you want to be able to represent them distinctly.
There are time-related objects where "the 26th hour" would make sense:
A "duration", representing an absolute amount of time, independent of when it happens.
An "interval", representing the span of time between two specific instants.
A "time of day", in certain specialised cases, where you want to consider the "day" to last more than 24 hours for planning purposes.
JavaScript doesn't currently have any of those built-in, although there are libraries that do, and a proposal for adding them natively.
It's likely that most "time of day" implementations would not allow for more than 24 hours in the day, but you could represent it using a "duration" or "interval". The end result might look something like this:
var timetableEntry = {
"date": Temporal.PlainDate.from({year: 2006, month: 8, day: 24}),
"startOffsetFromMidnight": Temporal.Duration.from({ hours: 23, minutes: 30 }),
"endOffsetFromMidnight": Temporal.Duration.from({ hours: 26, minutes: 30 })
}
var journeyDuration = timetableEntry.endOffsetFromMidnight.subtract( timetableEntry.startOffsetFromMidnight );
var startDateTime = timetableEntry.date.add( timetableEntry.startOffsetFromMidnight );
var endDateTime = timetableEntry.date.add( timetableEntry.endOffsetFromMidnight);

How to convert hours:minutes using javascript

I am currently working on Jvascript datetime part in that getting NaN error while converting hours and minutes to seconds like strtotime in PHP so I want to know how to convert minutes and seconds like the way we do in strtotime in PHP.
var d = new Date();
var total = d.getHours() + ":" + d.getMinutes();
var ts = Date.parse(total);
document.write(ts);
In output getting error NaN
This is a sort of inane question, but here's the number of seconds in the hours and minutes of that number:
var d = new Date();
var total = (d.getHours() * 60 * 60) + (d.getMinutes() * 60);
document.write(total);
First of all, Date.parse() takes a string of a specific format (such as Jul 18, 2018). Second, it will not convert the date to seconds, but will return the number of milliseconds since January 1, 1970 00:00:00 GMT.
If you need to convert hh:mm to seconds, the correct approach is to multiply the value of getHours() by 3600 and multiply the value of getMinutes() by 60, then sum up the two values.
var d = new Date();
var timeinsecs = d.getHours() * 3600 + d.getMinutes() * 60;
document.write(timeinsecs);
While if you need to get the time in seconds from January 1, 1970 00:00:00 GMT till the current time, you will need to parse the current date then divide by 1000:
var d = new Date();
document.write(Date.parse(d) / 1000);
Just get hours and minutes, then sum them multiplying hours * 3600 and minutes * 60, like this
var d = new Date();
var total = d.getHours() * 3600 + d.getMinutes() * 60;
document.write(total)
If you want to follow your original approach of not doing the math by hand, you need to include a date before the time (any date should do, could be today if you wish) and convert ms to seconds (both of these for the reasons Wais Kamal pointed out) as follows.
var d = new Date();
var total = d.getHours() + ":" + d.getMinutes();
var someDate ='July 4, 1776';//works, but maybe safer to choose since 1990
total=someDate+', '+total;
var ts = Date.parse(total);
document.write((ts- Date.parse(someDate))/1000);

Get next occurrence of day and hour in javascript

I am attempting to implement a countdown timer to a specific point in time in the future. This point in time is always the same day of the week and hour, and is based on UTC time.
I am attempting to write a general function that given a day of the week and an hour, it will return a date object that represents that criteria in the future.
Examples:
getNextOccuranceOfUTCDayAndHour(1, 7);
Get the next occurrence of 7 am on Monday. If today is Monday, 5/25/2015 # midnight UTC, then this function should return a Date object representing Monday 6/1/2015 7 am UTC.
getNextOccuranceOfUTCDayAndHour(3, 13);
Get the next occurrence of 1 pm on Wednesday. If today is Tuesday, 5/26/2015 # midnight UTC, then this function should return a Date object representing Wednesday 5/27/2015 1 pm UTC.
I have attempted to write a function to do this and I have included the snippet below, but it only seems to work for some dates and not others. It's incredibly unreliable. I would prefer not to use Moment.js.
function getNextOccuranceOfUTCDayAndHour(day, hour) {
d = new Date();
d.setDate(d.getUTCDate() + (7 + day - d.getUTCDay()) % 7)
d.setUTCHours(hour, 0, 0, 0);
return d;
}
function format_seconds(t) {
var d = Math.floor(t / 86400);
var h = Math.floor(t % 86400 / 3600);
var m = Math.floor(t % 3600 / 60);
var s = Math.floor(t % 3600 % 60);
return ((d > 0 ? d + " d. " : "") +
(h > 0 ? h + " h. " : "") +
(m > 0 ? m + " m. " : "") +
s + " s.");
}
function update() {
var next_occurance = getNextOccuranceOfUTCDayAndHour(1, 7);
$('#next_occurance').text(next_occurance);
var ms = next_occurance - new Date();
$('#countdown').text(format_seconds(Math.floor(ms / 1000)));
}
$(function() {
update();
setInterval(update, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="next_occurance">Next Occurance</p>
<p id="countdown">Countdown</p>
Edit: Some examples of expected vs. returned values. JSFiddle
The problem in the original code was the use of d.setDate(); instead of d.setUTCDate();. Additionally, if the current day was the same day of week as the target day, then the result was incorrect. Simply adding an if statement to check for this case fixes that problem.
Updated JSFiddle: https://jsfiddle.net/2j49q0ak/1

Javascript Count Days From Today

I would like a simple text box input of a date in the past and then for it to display how many days it is from today's date. I have found several examples of how to use javascript to do it between two dates that you input, but not with only doing one date and today's.
The current date to track is 4/2/2010, but it will change over time.
If you don't care about the leap second (:)), you can simply subtract the current date from the date back then, which gets you the difference in milliseconds, and then divide the difference by the amount of milliseconds that fits in one day:
var then = new Date(2010, 03, 02), // month is zero based
now = new Date; // no arguments -> current date
// 24 hours, 60 minutes, 60 seconds, 1000 milliseconds
Math.round((now - then) / (1000 * 60 * 60 * 24)); // round the amount of days
// result: 712
Here is a script I use for countdown timers. You can take out whatever parts you dont need to display just a day, time etc.
dateFuture = new Date(2029,2,4,23,59,59);
function GetCount(){
dateNow = new Date();
//grab current date
amount = dateFuture.getTime() - dateNow.getTime();
//calc milliseconds between dates
delete dateNow;
// time is already past
if(amount < 0){
document.getElementById('countbox').innerHTML="Now!";
}
// date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
if(days != 0){out += days +" day"+((days!=1)?"s":"")+",<br />";}
if(days != 0 || hours != 0){out += hours +" hour"+((hours!=1)?"s":"")+",<br />";}
if(days != 0 || hours != 0 || mins != 0){out += mins +" minute"+((mins!=1)?"s":"")+",<br />";}
out += secs +" seconds";
document.getElementById('countbox').innerHTML=out;
setTimeout("GetCount()", 1000);
}
}
window.onload=function(){GetCount();}//call when everything has loaded
<div id="countbox"><div>

Javascript, Hour comparisson

Having two strings (start and end time) in such form "16:30", "02:13" I want to compare them and check if the gap is greater than 5 mins.
How can this be achieved in Javascript in an easy way?
function parseTime(time) {
var timeArray = time.split(/:/);
// Using Jan 1st, 2010 as a "base date". Any other date should work.
return new Date(2010, 0, 1, +timeArray[0], +timeArray[1], 0);
}
var diff = Math.abs(parseTime("16:30").getTime() - parseTime("02:13").getTime());
if (diff > 5 * 60 * 1000) { // Difference is in milliseconds
alert("More that 5 mins.");
}
Do you need to wrap over midnight? Then this is more difficult. For example, 23:59 and 00:01 will produce a difference of 23 hours 58 minutes and not 2 minutes.
If that's the case you need to define your case more closely.
You can do as following:
if (((Date.parse("16:30") - Date.parse("02:13")) / 1000 / 60) > 5)
{
}
// time is a string having format "hh:mm"
function Time(time) {
var args = time.split(":");
var hours = args[0], minutes = args[1];
this.milliseconds = ((hours * 3600) + (minutes * 60)) * 1000;
}
Time.prototype.valueOf = function() {
return this.milliseconds;
}
// converts the given minutes to milliseconds
Number.prototype.minutes = function() {
return this * (1000 * 60);
}
Subtracting the times forces the object to evaluate it's value by calling the valueOf method that returns the given time in milliseconds. The minutes method is another convenience method to convert the given number of minutes to milliseconds, so we can use that as a base for comparison throughout.
new Time('16:30') - new Time('16:24') > (5).minutes() // true
This includes checking whether midnight is between the two times (as per your example).
var startTime = "16:30", endTime = "02:13";
var parsedStartTime = Date.parse("2010/1/1 " + startTime),
parsedEndTime = Date.parse("2010/1/1 " + endTime);
// if end date is parsed as smaller than start date, parse as the next day,
// to pick up on running over midnight
if ( parsedEndTime < parsedStartTime ) ed = Date.parse("2010/1/2 " + endTime);
var differenceInMinutes = ((parsedEndTime - parsedStartTime) / 60 / 1000);
if ( differenceInMinutes > 5 ) {
alert("More than 5 mins.");
}

Categories

Resources