Could not calculate the time difference using JavaScript - javascript

I need to calculate time difference in hrs in between current date time and user input date time using JavaScript. Here is my code:
var user_date = '31-03-2019';
var dep_time='12:30PM';
var datePieces = user_date.split("-");
var mydate=[datePieces[1] , datePieces[0] , datePieces[2]].join("-");
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = '0' + todayDay;
}
if (todayMonth < 10) {
todayMonth = '0' + todayMonth;
}
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(mydate);
var todayToDate = Date.parse(todayDateText);
//console.log(inputToDate, todayToDate);
//console.log(user_date, todayDateText);
if (inputToDate > todayToDate) {
var date=new Date;
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var timeStart = new Date(todayToDate + strTime);
var timeEnd = new Date(mydate + dep_time);
console.log(timeStart);
console.log(timeEnd);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
alert(hours);
} else {
}
Here I getting the output NAN . I have both user input and current date time and I need the time difference in HRS.

1) The Date.parse method turns a date into milliseconds since January 1st, 1970. See https://www.w3schools.com/Jsref/jsref_parse.asp, therefore turning your user input date into milliseconds since January 1st, 1970.
2) In Javascript, the getTime() method on the new Date() object gets the number of milliseconds that have passed since January 1, 1970 until the current time.
3) Therefore, finding the difference of these milliseconds gives you the difference in milliseconds.
4) Since 1 hour = 3600000 ms, to find the difference in hours, divide your answer by 3600000, and get the difference in hours.
You also seem to forget to include the dep_time in parsing your date.
And the solution is below:
<script>
"use strict";
var user_date = '31-03-2019 12:30 PM';
var datePieces = user_date.split("-");
var mydate=[datePieces[1] , datePieces[0] , datePieces[2]].join("-");
var todayDate = new Date();
var todayToDate = todayDate.getTime();
// In JavaScript, getTime() gets the number of milliseconds that have passed since January 1, 1970.
var inputToDate = Date.parse(mydate);
if (inputToDate > todayToDate) {
var diff = (inputToDate - todayToDate) / 3600000; //Since 1 h = 3600000 ms
alert(diff);
} else {
var diff = (todayToDate - inputToDate) / 3600000; //Since 1 h = 3600000 ms
alert(diff);
}
</script>

Related

display current dates hours and minute

I am facing an issue in javascript dates. i want to do minutes and second from current date.
My code:
date = new Date();
currentdate = new Date();
newCurrent = GetFormattedDate(currentdate);
GetFormattedDate(date) {
hour = ("0" + (date.getHours())).slice(-2);
min = ("0" + (date.getMinutes())).slice(-2);
return hour + ":" + min; //output 18:43
}
expected output:
`18:00` //if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00
`18:30` //if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30
What should I do? anyone help me?
var d = new Date();
var myTime = d.getHours() +':'+ (d.getMinutes() <= 29 ? '00' : '30') ;
template string:
const d = new Date();
const myTime = `${d.getHours()}:${d.getMinutes() <= 29 ? '00' : '30'}` ;
or
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var altedMinutes = minutes <= 29 ? '00' : '30';
var displayTime = hours + ':' + altedMinutes;
If you want PM/AM
var suffix = 'AM'
var hours = now.getHours()
if (hours>11) {
hours - =12;
suffix = 'PM'
}
...
var displayTime = hours + ':' + altedMinutes + ' ' + suffix;

Check if current time is between two given times in JavaScript

I have two variables called 'startTime' and 'endTime'.
I need to know whether current time falls between startTime and EndTime. How would I do this using JavaScript only?
var startTime = '15:10:10';
var endTime = '22:30:00';
var currentDateTime = new Date();
//is current Time between startTime and endTime ???
UPDATE 1:
I was able to get this using following code. You can check out the code at: https://jsfiddle.net/sun21170/d3sdxwpb/1/
var dt = new Date();//current Date that gives us current Time also
var startTime = '03:30:20';
var endTime = '23:50:10';
var s = startTime.split(':');
var dt1 = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(),
parseInt(s[0]), parseInt(s[1]), parseInt(s[2]));
var e = endTime.split(':');
var dt2 = new Date(dt.getFullYear(), dt.getMonth(),
dt.getDate(),parseInt(e[0]), parseInt(e[1]), parseInt(e[2]));
alert( (dt >= dt1 && dt <= dt2) ? 'Current time is between startTime and endTime' :
'Current time is NOT between startTime and endTime');
alert ('dt = ' + dt + ', dt1 = ' + dt1 + ', dt2 =' + dt2)
var startTime = '15:10:10';
var endTime = '22:30:00';
currentDate = new Date()
startDate = new Date(currentDate.getTime());
startDate.setHours(startTime.split(":")[0]);
startDate.setMinutes(startTime.split(":")[1]);
startDate.setSeconds(startTime.split(":")[2]);
endDate = new Date(currentDate.getTime());
endDate.setHours(endTime.split(":")[0]);
endDate.setMinutes(endTime.split(":")[1]);
endDate.setSeconds(endTime.split(":")[2]);
valid = startDate < currentDate && endDate > currentDate
You can possibly do something like this if you can rely on your strings being in the correct format:
var setDateTime = function(date, str){
var sp = str.split(':');
date.setHours(parseInt(sp[0],10));
date.setMinutes(parseInt(sp[1],10));
date.setSeconds(parseInt(sp[2],10));
return date;
}
var current = new Date();
var c = current.getTime()
, start = setDateTime(new Date(current), '15:10:10')
, end = setDateTime(new Date(current), '22:30:00');
return (
c > start.getTime() &&
c < end.getTime());
I wanted to compare a time range in the day ... so I wrote this simple logic where the time is converted into minutes and then compared.
const marketOpen = 9 * 60 + 15 // minutes
const marketClosed = 15 * 60 + 30 // minutes
var now = new Date();
var currentTime = now.getHours() * 60 + now.getMinutes(); // Minutes since Midnight
if(currentTime > marketOpen && currentTime < marketClosed){ }
Note that I have not taken UTC minutes and hours since I want to use the local time, In my case it was IST time.
A different approach:
First, convert your currentDate
var totalSec = new Date().getTime() / 1000;
var hours = parseInt( totalSec / 3600 ) % 24;
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = totalSec % 60;
var numberToCompare = hours*10000+minutes*100+seconds;
cf Convert seconds to HH-MM-SS with JavaScript?
Then compare:
(numberToCompare < (endTime.split(':')[0]*10000+endTime.split(':')[1]*100+endTime.split(':')[2]*1)
or
(numberToCompare > (endTime.split(':')[0]*10000+endTime.split(':')[1]*100+endTime.split(':')[2]*1)
Just another way I have for matching periods in a day, precision is in minutes, but adding seconds is trivial.
function isValid(date, h1, m1, h2, m2) {
var h = date.getHours();
var m = date.getMinutes();
return (h1 < h || h1 == h && m1 <= m) && (h < h2 || h == h2 && m <= m2);
}
isValid(new Date(), 15, 10, 22, 30);

how to convert the minutes into hours and minutes with subtracted time(subtracted time values)

I want to subtract the two different 24 hours time format.
I had tried with following :
var startingTimeValue = 04:40;
var endTimeValue = 00:55;
var hour = startingTimeValue.split(":");
var hour1 = endTimeValue.split(":");
var th = 1 * hour[0] - 1 * hour1[0];
var tm = 1 * hour[1] - 1 * hour1[1];
var time = th+":"+tm;
This code is working fine if second minutes is not greater than the first.but other case it will return minus values.
The above code sample values result :
time1 : 04:40
time2 : 00:55
The result should be : 03:45 (h:mi) format.
But right now I am getting 04:-5 with minus value.
I had tried with the link as : subtract minutes from calculated time javascript but this is not working with 00:00 format.
So how to calculate the result value and convert into hours and minutes?
I would try something like the following.
The way I see it, it is always better to break it down to a common unit and then do simple math.
function diffHours (h1, h2) {
/* Converts "hh:mm" format to a total in minutes */
function toMinutes (hh) {
hh = hh.split(':');
return (parseInt(hh[0], 10) * 60) + parseInt(hh[1], 10);
}
/* Converts total in minutes to "hh:mm" format */
function toText (m) {
var minutes = m % 60;
var hours = Math.floor(m / 60);
minutes = (minutes < 10 ? '0' : '') + minutes;
hours = (hours < 10 ? '0' : '') + hours;
return hours + ':' + minutes;
}
h1 = toMinutes(h1);
h2 = toMinutes(h2);
var diff = h2 - h1;
return toText(diff);
}
Try:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
var subtractedValue = time1 - time2;
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
DEMO
This solution utilizes javascript built-in date. How it works:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
time1, time2 is the number of miliseconds since 01/01/1970 00:00:00 UTC.
var subtractedValue = time1 - time2;
subtractedValue is the difference in miliseconds.
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
These lines reconstruct a date object to get hours and minutes.
This works better , A fiddle I just found
var difference = Math.abs(toSeconds(a) - toSeconds(b));
fiddle
This method may work for you:
function timeDiff(s,e){
var startTime = new Date("1/1/1900 " + s);
var endTime = new Date("1/1/1900 " + e);
var diff = startTime - endTime;
var result = new Date(diff);
var h = result.getUTCHours();
var m = result.getUTCMinutes();
return (h<=9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m);
}
var startingTimeValue = "04:40";
var endTimeValue = "00:55";
var formattedDifference = timeDiff(startingTimeValue,endTimeValue);
Demo: http://jsfiddle.net/zRVSg/

How to keep updating datetime every minute in Javascript?

I am using following code to display date on my webpage. I need to update it every minute. How to do that?
var d=new Date();
var n=d.toString();
document.write(n);
Currently its static, means when the page load, datetime of that moment is displayed. I have to update time every minutes without refreshing the page.
Try with setInterval(): http://jsfiddle.net/4vQ8C/
var nIntervId; //<----make a global var in you want to stop the timer
//-----with clearInterval(nIntervId);
function updateTime() {
nIntervId = setInterval(flashTime, 1000*60); //<---prints the time
} //----after every minute
function flashTime() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time); //<----updates the time in the $('#my_box1') [needs jQuery]
}
$(function() {
updateTime();
});
You can use document.getElementById("my_box1").innerHTML=time; instead of $('#my_box1')
from MDN:
About setInterval : --->Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
About setTimeout : ----> Calls a function or executes a code snippet after specified delay.
Here is how you can print date time every second
function displayDate()
{
var n=BuildDateString();
document.write(n);
window.setTimeout("displayDate();", 1000); // to print it every minute take 1000*60
}
function BuildDateString()
{
var today = new Date()
var year = today.getYear()
if (year < 2000)
year = "19" + year
var _day = today.getDate()
if (_day < 10)
_day = "0" + _day
var _month = today.getMonth() + 1
if (_month < 10)
_month = "0" + _month
var hours = today.getHours()
var minutes = today.getMinutes()
var seconds = today.getSeconds()
var dn = "AM"
if (hours > 12)
{
dn = "PM"
hours = hours - 12
}
if (hours == 0)
hours = 12
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
var DateString = _month+"/"+_day+"/"+year+" "+hours+":"+minutes+":"+seconds+" "+dn
return DateString;
}
I am using following approach:
var myVar=setInterval(function(){myDateTimer()},60000);
function makeArray()
{
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}
function myDateTimer()
{
var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
document.getElementById("showDateTime").innerHTML=finaldate;
}
just do this
$(function(){
setInterval(function(){
var d=new Date();
var n=d.toString();
$('#test').html(n);
},1000);
});
demo http://runjs.cn/code/txlexzuc

Javascript - How can I work out the difference between two given times? (hours-minutes)

I have two sets of 'select' elements where the user can enter in two times. It looks like this:
Start:
[hour] [minute] [meridian]
End:
[hour] [minute] [meridian]
I'm trying to take those times and figure out the difference. So I can then output:
Difference: 1.25 HRS
The decimal format, as you probably know, means 1 hour and 15 minutes.
There's also a checkbox the user can click which, if selected, will take away 30 minutes. Here's what my current code looks like:
var startHours = parseInt($start.find('.times:eq(0)')[0].value);
var startMinutes = parseInt($start.find('.times:eq(1)')[0].value);
var startMeridian = $start.find('.times:eq(2)')[0].value
if (startMeridian == 'PM')
startHours += 12;
var finishHours = parseInt($finish.find('.times:eq(0)')[0].value);
var finishMinutes = parseInt($finish.find('.times:eq(1)')[0].value);
var finishMeridian = $finish.find('.times:eq(2)')[0].value
if (finishMeridian == 'PM')
finishHours += 12;
// compute the difference
var completeHours = finishHours - startHours;
var completeMinutes = finishMinutes - startMinutes;
var newTime = 0;
if (completeHours < 0 || completeMinutes < 0)
newTime = '0.0';
else
newTime = completeHours + '.' + completeMinutes;
var hadBreak = $parent.parents('tr').next('tr').find('.breakTaken')[0].checked;
if (hadBreak)
{
time = newTime.split('.');
hours = time[0];
minutes = time[1];
minutes = minutes - 30;
if (minutes < 0)
{
minutes = 60 - (minutes * 1);
hours = hours - 1;
}
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
}
$parent.parents('tr').next('tr').find('.subtotal')[0].innerHTML = newTime;
total += parseFloat(newTime);
It's failing... What am I doing wrong?
To save you some hassle, I would recommend using the Date object, which is very convenient:
var startDate = new Date(year, month, date, hour, minute, second, millisecond);
var endDate = new Date(year, month, date, hour2, minute2, second2, millisecond2);
// You can skip hours, minutes, seconds and milliseconds if you so choose
var difference = endDate - startDate; // Difference in milliseconds
From there you can calculate the days, hours and minutes that passed between those two dates.
The line
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
is wrong - minutes might be 15, but you want it to print out the fraction. Hence you need:
var MinutesDisplay = minutes/60*100;
newTime = (hours < 0) ? '0.0' : hours + '.' + (MinutesDisplay.toFixed(0));

Categories