I am getting the time duration correctly for 24 hrs format but for 12 hrs format I am getting error if i give 11:00 am to 1:00 pm. If I give 10:00 am to 11:00 am it will correctl and if I give 6:00 pm to 7:00 pm it will give correctly only in am to pm i m facing problem.
function autoChangeDuration() {
var diff1 = "00:00";
var start = document.getElementById("startTime").value;
var end = document.getElementById("endTime").value;
if (start > end) {
document.getElementById("duration").value = diff1;
} else {
var space1 = start.split(' ');
var space2 = end.split(' ');
s = space1[0].split(':');
e = space2[0].split(':');
var diff;
min = e[1] - s[1];
hour_carry = 0;
if (min < 0) {
min += 60;
hour_carry += 1;
}
hour = e[0] - s[0] - hour_carry;
diff = hour + ":" + min;
document.getElementById("duration").value = diff;
}
function toDate(s) {
// the date doesn't matter, as long as they're the same, since we'll
// just use them to compare. passing "10:20 pm" will yield 22:20.
return new Date("2010/01/01 " + s);
}
function toTimeString(diffInMs) {
// Math.max makes sure that you'll get '00:00' if start > end.
var diffInMinutes = Math.max(0, Math.floor(diffInMs / 1000 / 60));
var diffInHours = Math.max(0, Math.floor(diffInMinutes / 60));
diffInMinutes = diffInMinutes % 60;
return [
('0'+diffInHours).slice(-2),
('0'+diffInMinutes).slice(-2)
].join(':');
}
function autoChangeDuration()
{
var start = document.getElementById("startTime").value;
var end = document.getElementById("endTime").value;
start = toDate(start);
end = toDate(end);
var diff = (end - start);
document.getElementById("duration").value = toTimeString(diff);
}
Why don't you just use javascript's Date class?
http://www.w3schools.com/jsref/jsref_obj_date.asp
Related
I want to calculate my work time. It works fine when I input
08:00 - 09:00 = 01:00
But when I input this time
23:30 - 01:30 = 10:00
It should return 02:00
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime(start, end) {
var s = start.split(":"),
sMin = +s[1] + s[0] * 60,
e = end.split(":"),
eMin = +e[1] + e[0] * 60,
diff = eMin - sMin;
if (diff < 0) {
sMin -= 12 * 60;
diff = eMin - sMin
}
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick = function() {
document.getElementById('delay').value = diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">
I would use a Date object to calculate the difference in time. Since you are only interested in the time, you can use any date to construct a valid date string. The reason why you are getting 10 hours is because there is no date to show that it is 1am the following day (this is from my understanding of your question).
You can do something like below to get the job done.
const pad = num => (num < 10) ? `0${num}` : `${num}`;
const addADay = (start, end) => {
const sHour = parseInt(start.split(':')[0], 10);
const eHour = parseInt(end.split(':')[0], 10);
return (eHour < sHour);
};
const diffTime = (start, end) => {
const startDate = new Date(`2019/01/01 ${start}:00`);
const endDate = addADay(start, end)
? new Date(`2019/01/02 ${end}:00`)
: new Date(`2019/01/01 ${end}:00`);
const diff = endDate.getTime() - startDate.getTime();
const hours = Math.floor(diff / 3600000);
const min = (diff - (hours * 3600000)) / 60000;
return `${pad(hours)}:${pad(min)}`;
}
console.log(diffTime('08:00','09:00')); // returns 01:00
console.log(diffTime('23:00','01:30')); // returns 02:30
The most important part in the required algorithm is finding if the end date is tomorrow.
based on your code here is a working example with my suggestion.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button" onclick="diffTime()">CLICK
</button>
<input type="time" id="delay">
<script>
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime() {
var start = document.getElementById("timeOfCall").value;
var end = document.getElementById("timeOfResponse").value;
// start date will be today
var d1 = new Date();
var s = start.split(":")
var date1 = new Date(d1.getFullYear(),d1.getMonth(),d1.getDate(),s[0],s[1],0,0);
var s2 = end.split(":")
// end date
if(s2[0] < s[0])
{
// its tommorow...
var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);
d1=tomorrow;
}
var date2 = new Date(d1.getFullYear(),d1.getMonth(),d1.getDate(),s2[0],s2[1],0,0);
var diff = date2.getTime() - date1.getTime();
var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;
alert(hh + ":" + mm + ":" + ss);
}
document.getElementById("timeOfCall").defaultValue = "23:30";
document.getElementById("timeOfResponse").defaultValue = "01:30";
</script>
</body>
</html>
Hello I have change your code slightly. The explanation is, let your start time is 10:00 and end time is 09:00. Now think with clock wise. the time had to go to 9:00 with 24 hours. So the calculation is difference between 24 and 10 hours and add the rest of the time.
D = E + (24 - S)
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime(start, end) {
var s = start.split(":"),
sMin = +s[1] + s[0] * 60,
e = end.split(":"),
eMin = +e[1] + e[0] * 60,
diff = eMin - sMin;
if (diff < 0) {
diff = eMin + (24 * 60 - sMin); /* You had to caculate with 24 hours */
}
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick = function() {
document.getElementById('delay').value = diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">
Here is another simpler way to look at the problem which satisfies all of your test cases, try your all test cases if any case fails then tell me i will fix it.
you just take the hours first and then check if is am or pm and then simply count the minutes.
function diffTime(start, end) {
var s = start.split(":");
var e = end.split(":");
var dHour;
var dMinute ;
var startHour = parseInt(s[0]);
var endHour = parseInt(e[0]);
var startMinute = parseInt(s[1]);
var endMinute = parseInt(e[1]);
// For counting difference of hours
if((startHour>12 && endHour>12) || (startHour<12 && endHour<12))
{
if(startHour<endHour)
{
dHour = endHour - startHour;
}
else if(startHour>endHour)
{
dHour = 24 - ( startHour - endHour);
}
else
{
dHour = 24;
}
}
else if(startHour>12 && endHour<=12)
{
dHour = (24 - startHour) + endHour;
}
else if(startHour<=12 && endHour > 12)
{
dHour = endHour - startHour;
}
else
{
dHour = 24
}
// For Counting Difference of Minute
if (startMinute>endMinute)
{
dMinute = 60 - (startMinute - endMinute);
dHour = dHour - 1;
}
else if(startMinute<endMinute)
{
dMinute = endMinute - startMinute;
}
else
{
dMinute = 0
}
return dHour + " Hours " + dMinute + " Minutes";
}
document.getElementById('button').onclick = function() {
document.getElementById('delay').value = diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="text" id="delay">
thank you friend i solve my problem, Miraz Chowdhury's code has done my job
function diff(t1, t2) {
const day = 86400000;
function pad(num) {
return ("0" + num).slice(-2);
}
let time1 = t1.split(":").map(el => parseInt(el));
let time2 = t2.split(":").map(el => parseInt(el));
let zero = (new Date(1990, 0, 1, 0, 0)).setMilliseconds(0)
let aaa = (new Date(1990, 0, 1, time1[0], time1[1])).setMilliseconds(0)
let bbb = (new Date(1990, 0, 1, time2[0], time2[1])).setMilliseconds(0)
let diff = day -Math.abs(aaa - bbb)<Math.abs(aaa - bbb)?day -Math.abs(aaa - bbb):Math.abs(aaa - bbb)
return `${pad(Math.round(diff/1000/60/60))}:${pad(Math.abs(Math.round(diff/1000/60%60)))}`;
}
console.log(diff("09:00", "08:00"));
console.log(diff("23:30", "01:30"));
console.log(diff("01:30", "23:30"));
In my application, I need to create live clock according to different timezones which are stored into database.
I have almost succeeded it.
But now I'm facing negative time in clock, and I'm out of ideas to figure out a solution.
I'm getting UTC time with the help of new Date() and calculating time with provided timezone from database.
Case 1: 0:31 (UTC time) + 5:30 (timezone) = '06:01'
Case 2: 06:31 (UTC time) - 6:30 (timezone) = '00:01'
Case 3: 5:0 (UTC time) - 7:0 (timezone) = '-02:00'
Case 1 and 2 is working properly but I'm getting negative value in 3rd case which is wrong.
I have tried to add comments in code to have better understanding of what I'm doing here. I hope it helps.
Any help will be highly appreciated.
function runClock() {
setInterval(function() {
//debugger
var time = new Date();
// take timezone from HTML element
// ex: +:5:30
var getTimezone = "-:7:0" //$("#timeZone").text();
// split into array to get oparator (Positive and Negative Timezone)
var oparator = getTimezone.split(":")[0];
var timezone = getTimezone.split(":")[1] + ":" + getTimezone.split(":")[2];
// get UTC hours
var hours = 5 //time.getUTCHours();
var minutes = 0 //time.getUTCMinutes();
var UTCTIME = timeStringToFloat(hours + ":" + minutes);
var TIMEZONEOFFSETTIME = timeStringToFloat(timezone);
var finalTime = "";
// Convert time folloed by Colon into decimals
// ex: 1:45 = 1.75
function timeStringToFloat(time) {
var hoursMinutes = time.split(/[.:]/);
var hh = parseInt(hoursMinutes[0], 10);
var mm = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return hh + mm / 60;
}
// Convert time folloed by float into Colon
// ex: 1.75 = 1:45
function floatToTime(FT) {
var splittedTime = FT.toString().split(".");
var hh = splittedTime[0];
var mm = "";
if (splittedTime[1]) {
mm = Math.round((splittedTime[1] / 100) * 60);
} else {
mm = "0";
}
finalTime = hh + ":" + ((mm < 10) ? ("0" + mm) : mm);
}
// Calculate time (UTC + or - Timezone)
// Ex: 00:15 (UTC) + 5:30 = 5:45
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
}
}
// Parse Seconds
function seconds() {
var j = "";
if (time.getUTCSeconds() < 10) {
j = "0" + time.getUTCSeconds();
} else {
j = time.getUTCSeconds()
}
return j;
}
CalcTime(UTCTIME, TIMEZONEOFFSETTIME);
$("#clockTime").text(finalTime + ":" + seconds());
}, 1000);
}
runClock();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b id="clockTime"></b>
You should just be "looping back" to 23:59 when you go negative. You can just add something to check if it goes negative then just re-add the missing time:
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
// Offset any negative times;
if (FT < 0) {
FT += 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
}
But ideally you really don't want to be handling these kinds of Timezone issues as other libraries are already handling it, i.e. moment.js
function runClock() {
setInterval(function() {
//debugger
var time = new Date();
// take timezone from HTML element
// ex: +:5:30
var getTimezone = "-:7:0" //$("#timeZone").text();
// split into array to get oparator (Positive and Negative Timezone)
var oparator = getTimezone.split(":")[0];
var timezone = getTimezone.split(":")[1] + ":" + getTimezone.split(":")[2];
// get UTC hours
var hours = 5 //time.getUTCHours();
var minutes = 0 //time.getUTCMinutes();
var UTCTIME = timeStringToFloat(hours + ":" + minutes);
var TIMEZONEOFFSETTIME = timeStringToFloat(timezone);
var finalTime = "";
// Convert time folloed by Colon into decimals
// ex: 1:45 = 1.75
function timeStringToFloat(time) {
var hoursMinutes = time.split(/[.:]/);
var hh = parseInt(hoursMinutes[0], 10);
var mm = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return hh + mm / 60;
}
// Convert time folloed by float into Colon
// ex: 1.75 = 1:45
function floatToTime(FT) {
var splittedTime = FT.toString().split(".");
var hh = splittedTime[0];
var mm = "";
if (splittedTime[1]) {
mm = Math.round((splittedTime[1] / 100) * 60);
} else {
mm = "0";
}
finalTime = hh + ":" + ((mm < 10) ? ("0" + mm) : mm);
}
// Calculate time (UTC + or - Timezone)
// Ex: 00:15 (UTC) + 5:30 = 5:45
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
// Offset any negative times;
if (FT < 0) {
FT += 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
}
// Parse Seconds
function seconds() {
var j = "";
if (time.getUTCSeconds() < 10) {
j = "0" + time.getUTCSeconds();
} else {
j = time.getUTCSeconds()
}
return j;
}
CalcTime(UTCTIME, TIMEZONEOFFSETTIME);
$("#clockTime").text(finalTime + ":" + seconds());
}, 1000);
}
runClock();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b id="clockTime"></b>
You want to recover/display the time for a given timezone offset? Unless you like doing this for a hobby, stay away from string methods and use the date functions, no?
var offsetMS = -5.5 * 3600000
var myDate = new Date()
var dateWithOffset = new Date( myDate.getTime() + offsetMS )
var formatted = dateWithOffset.toLocaleString("en-GB",{timeZone:"UTC",hour:"numeric",minute:"numeric"})
console.log(formatted)
Even manipulating timezone offset directly is to be avoided. If you can, use toLocaleString with a real timezone name, then issues like daylight saving will be handled for you. Modern browsers support all iana timezones, so let them do the work.
Add 24 to your FT value and take division remain of 24:
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME + 24;
FT = FT % 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
Working sample: https://codepen.io/anon/pen/VqQqoo
If you do not want to use a library like moment.js that comes with time zone handling and simply need to add/subtract hours from a given date, how about converting them to a common time unit and operating on that?
const timezoneString = '-:12:30';
const parts = timezoneString.split(':');
const timezone = (parts[0] === '-' ? -1 : 1) * (parseInt(parts[1]) + (parseInt(parts[2]) / 60.0));
const timeZoneMillis = timezone * 3600 * 1000;
const now = new Date();
const inZone = new Date(now.getTime() + timeZoneMillis);
console.log(now, inZone);
Something like this would convert them to a millisecond timestamp and subtract that many hours and convert it back to a date.
I have two time values that should subtract and output the difference in hours. For example I get the values in this format:
0530-2400
That value is a string. I guess that converting to JavaScript Date object is the first step. Here is what I have so far:
var time = "0530-2400",
arr = [];
arr = time.split('-');
var dateObj = new Date(),
hours1 = dateObj.setHours(Number(arr[0].substring(0, 2))),
hours2 = dateObj.setHours(Number(arr[1].substring(0, 2))),
minutes1 = dateObj.setMinutes(Number(arr[0].substring(2, 4))),
minutes2 = dateObj.setMinutes(Number(arr[1].substring(2, 4)));
console.log(hours1);
console.log(minutes1);
console.log(hours2);
console.log(minutes2);
The output for the time I showed above should be 18.5 hours. If we subtract 24-5.5(530) = 18.5
The increments are always on 15,30 or 45 minutes. Is there a good way to convert string and then do the math in JS?
If there cannot be hours spanning multiple days, you can do it using simple math:
var time = "0530-2400",
difference = calcDifference(time);
console.log(difference);
function calcDifference(time) {
var arr = time.split('-').map(function(str) {
var hours = parseInt(str.substr(0, 2), 10),
minutes = parseInt(str.substr(2, 4), 10);
return (hours * 60 + minutes) / 60;
});
return arr[1] - arr[0];
}
Here you go:
var time = "0530-2400",
arr = [];
arr = time.split('-');
var date1 = new Date(), date2 = new Date();
date1.setHours(Number(arr[0].substring(0, 2)));
date2.setHours(Number(arr[1].substring(0, 2)));
date1.setMinutes(Number(arr[0].substring(2, 4)));
date2.setMinutes(Number(arr[1].substring(2, 4)));
var msInAHour = 1000*60*60;
var msDiff = date2 - date1;
var diffInHours = msDiff/msInAHour;
console.log(diffInHours.toFixed(1));
Hint: It's a lot easier to work with dates if you use Moment.js.
Here: https://momentjs.com/
Here's a more advanced version of the code:
var dt = "0530-2400".split('-')
.map(e=>new Date('1980-01-01'+e.replace(/(\d{2})(\d{2})/," $1:$2")));
var diffInHours = ((dt[1]-dt[0])/(3600000)).toFixed(1);
console.log(diffInHours);
var totalmin = 18.5*60
var min = total % 60;
var hours = (totalmin - min)/ 60;
min: 30, hours: 18
If you want to convert military hours to standard:
if (hours > 0 && hours <= 12) {
var standardHours= "" + hours;
} else if (hours > 12) {
var standardHours= "" + (hours - 12);
} else if (hours == 0) {
var standardHours= "12";
}
standardHours: 6
So let's say we have two times:
7:30 - 12:00
So my question is how can I generate an array with times like this:
7:30, 8:00, 8:30, 9:00, 9:30, 10:00, 10:30, 11:00, 11:30
I need this for a booking, so let's say the business will open at 7:30 and every booking that you can make will be 30 min(this time can change, could be one hour or more)
Whats the best way to generate something like this in JS?
Little verbose utility, you can use it..
var getTimeIntervals = function (time1, time2, slotInMinutes, workingHourStart, workingHourEnd) {
time1.setMinutes(0); time1.setSeconds(0);
var arr = [];
var workingHoursStart = workingHourStart;
var workingHourEnds = workingHourEnd;
var workingHourStartFloat = parseFloat("7:30");
var workingHourEndFloat = parseFloat("12:00");
while(time1 < time2){
var generatedSlot = time1.toTimeString().substring(0,5);
var generatedSlotFloat = parseFloat(generatedSlot);
time1.setMinutes(time1.getMinutes() + slotInMinutes);
if(generatedSlotFloat >= workingHourStartFloat && generatedSlotFloat < workingHourEndFloat){
var generatedObject = {
slot: time1.toTimeString().substring(0,5),
timeStamp: new Date(time1.getTime())
};
arr.push(generatedObject);
}
}
return arr;
}
var today = new Date();
var tomrorow = new Date().setDate(today.getDate()+1);
console.log(getTimeIntervals(today, tomorrow, 30, "7:30", "12:00"));
Function getTimeIntervals expects startDate, endDate, slotDurationInMinutes, workingHoursStart and workingHourEnd.
Why I am returning object is because you may need the timestamp of selected slot in your further application use.
Fiddle - https://jsfiddle.net/rahulrulez/t8ezfj2q/
As the comment in the code says, you can remove the 0 before the hours if you don't want it, by removing that line.
If you don't want the end in the array just replace the <= by <in the for loop
function timeArray(start, end){
var start = start.split(":");
var end = end.split(":");
start = parseInt(start[0]) * 60 + parseInt(start[1]);
end = parseInt(end[0]) * 60 + parseInt(end[1]);
var result = [];
for ( time = start; time <= end; time+=30){
result.push( timeString(time));
}
return result;
}
function timeString(time){
var hours = Math.floor(time / 60);
var minutes = time % 60;
if (hours < 10) hours = "0" + hours; //optional
if (minutes < 10) minutes = "0" + minutes;
return hours + ":" + minutes;
}
console.log(timeArray("7:30", "12:00"));
A shorter version:
timeArray = [];
....
let i = 0;
let hour = 8;
let odd: boolean;
do {
odd = false;
if (i % 2 === 0) {
odd = true;
hour--;
}
this.timeArray.push(hour.toString() + (odd ? ":30" : ":00"));
i++;
hour++;
} while (i < 12);
....
Demo
I want to do a JavaScript loop based on two times (in military format), and that loop have to return a normal time.
For instance, I have this two vars:
var start_time = 1400; // That mens 14:00 or 2pm
var end_time = 400; // Or 0400 (but it's the same the browser. It's 04:00 or 4 am
I want to do a loop, a for or while, and I want to give as a result this:
14:00
15:00
16:00
....
3:00
4:00
How I can do that? Thanks!
start_time = start_time / 100;
end_time = end_time / 100;
var x = start_time;
while(x >= start_time || x <= end_time) {
if(x > 23) {
x = 0;
}
console.log(x + ":00");
x = x + 1;
}
http://jsfiddle.net/4R8Dr/1/
The general idea (room for improvement):
var start = 1400;
var end = 400;
if (start > end){
end = end + 2400;
}
for (var i = start; i <= end; i += 100)
{
var c = (i % 2400);
var s = c + '';
console.log(s.substring(0, c < 1000 ? 1 : 2) + ':00');
}
Output with node:
14:00
15:00
16:00
17:00
18:00
19:00
20:00
21:00
22:00
23:00
0:00
1:00
2:00
3:00
4:00
Loop in a for, incrementing the hour by 100.
Just make sure to reset loop variable to 0:00 when you reach 24:00
function loopHours(start_time, end_time) {
function write(hour){
console.log( (hour/100) + ":00" );
}
var hour = start_time;
for (; hour != end_time; hour += 100) {
if (hour >= 2400) {
hour = 0;
}
write(hour);
}
write(end_time);
}
getFormattedTime = function (fourDigitTime) {
var hours24 = parseInt(fourDigitTime.substring(0, 2), 10);
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = fourDigitTime.substring(2);
return hours + ':' + minutes + amPm;
};
$('span.mil_time').html(function (i, oldHtml) {
return getFormattedTime(oldHtml);
});
Plus a loop that increase/decreases the variable by 100 and resets at 2400 to 0000 will do what you need. Don't forget this function requires jQuery and span tags with the id "mil_time"
http://jsfiddle.net/FsN6L/