Difference between two dates by using angularjs? - javascript

This is my code
var departureDateFormat = new Date("10/09/15T09:25:00");
var arrivalDateFormat = new Date("13/09/15T13:25:00");
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[2];
var duration = moment.duration(arrivalDateFormat - departureDateFormat); //for reference of moment.js
var minutes = (duration / (1000 * 60)) % 60; // calliculating number of minutes
var hours = ((moment.duration(arrivalDateFormat - departureDateFormat)).humanize()); // calliculating number of hours
var timeInHours = ((hours == "an hour") ? 1 : hours.toString().substring(0, 1));
item.stopsDurationTime = timeInHours + "hrs " + minutes + "ms";
return timeInHours + "hrs " + minutes + "ms";
In the above code worked on IE , but it was not working on other browsers.Now i want to get difference between the above two dates by using angularJs/javascript.

You should use:
var minutes = duration.minutes();
var hours = duration.hours();
return hours + "hrs " + minutes + "ms";
Humanizing and then extracting the individual values is just unneeded overhead.
And moment can extract the hours and minutes for you so no need to compute from milliseconds.
Update:
Something like this:
var departureDate = moment("10/09/15T09:25:00", "DD/MM/YYYYTHH:mm:ss");
var arrivalDate = moment("13/09/15T13:35:10", "DD/MM/YYYYTHH:mm:ss");
var duration = moment.duration(arrivalDate.diff(departureDate));
var hours = Math.floor(duration.asHours());
var minutes = Math.floor(duration.asMinutes()-(hours*60));
return hours + "hrs " + minutes + "ms";
You have to define the format explicitly otherwise depending on your regional setting it will understand "10/09" as October, 9th or September, 10th.
Then you create a duration object. And you convert it to a number of hours (using "floor" to get a whole number). Then you convert it again to a number of minutes and subtract the hours you already got.

Related

How to add hours to string formatted as HH:MM:SS in 24 hour format

I'm trying to add hours to time in the format of 24 hours say '23:59:59'. I need to add, for example, 2.5 hours so the time should roll to the next day and be shown as '02:30:00'.
What I have tried so far works until it reaches '23:59:59'. I need to show the next day time if it exceeds '23:59:59'. Here is what I have tried so far:
var time = $('#starttime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var time2 = $('#endtime').val().split(':');
var endtimeval = new Date();
endtimeval.setHours(+time2[0]);
endtimeval.setMinutes(time2[1]);
endtimeval.setSeconds(time2[2]);
var str = d.getHours() + parseInt($('#noofhours').val()) + ":" + time2[1] + ":" + time2[2];
$('#endtime').val(str);
Using a Date Object here is possibly unnecessary, modulo arithmetic should suffice.
const pad = n => {
const s = String(n);
return s.length > 1 ? s : '0' + s;
};
const addHours = (timeVal, numHours) => {
const [hr, min, sec] = timeVal.split(':').map(Number);
const [,lefty, righty] = String(numHours).match(/(\d+)(?:(\.\d+))?/).map(Number);
const hours = (hr + lefty) % 24;
const minutes = righty === undefined ?
min :
((righty * 60 | 0) + min) % 60;
return [hours, minutes, sec].map(pad).join(':');
};
addHours('23:59:59', 2.5) // "01:29:59"
Note that since there's no dates involved it will not accurately handle e.g. daylight savings time. Also note that minutes are in this example rounded down, you could repeat the logic for seconds if desired.
Note that your approach using Date objects will give different answers for the same inputs depending on when/where the logic runs, for the same reasons.
Make a custom date adder?
const add = (time, hours) => {
let [hh, mm, ss] = time.split(':');
const seconds = hours * 60 * 60;
ss = ss * 1 + seconds;
if (ss >= 60) {
mm = mm * 1 + ss / 60;
ss = (ss % 60).toPrecision(2).padStart(2, '0');
}
if (mm >= 60) {
hh = hh * 1 + mm / 60;
mm = (mm % 60).toPrecision(2).padStart(2, '0');
}
hh = (Math.floor(hh) % 24).toString().padStart(2, '0');
return hh + ':' + mm + ':' + ss;
}
console.log(add("23:59:59", 2.5));
you may apply DRY principle and refactor the code yourself. But it will get the job done according to your requirement.
The simple trick that I did is just converted the hours entered as float/int to a minute value by multiplying to 60 and created a date, with this just added the time I already have.
Here the solution with minimal steps:
var time = $('#endtime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var addeddate = new Date();
addeddate.setMinutes(parseFloat($('#noofhours').val()) * 60);
$('#endtime').val(("0" + (addeddate.getHours())).slice(-2) + ":" + ("0" + (addeddate.getMinutes())).slice(-2) + ":" + ("0" + (addeddate.getSeconds())).slice(-2)); //The answer that I needed in endtime id value.
You can use vanilla JavaScript Date methods fairly easily here. Most of the work is parsing the time string inputs and then concatenating the time string output. For example:
const start = '23:59:59';
const add = '2.5';
const [hh, mm, ss] = start.split(':').map(x => parseInt(x));
const d = new Date(new Date().setHours(hh, mm + (add * 60), ss));
const end = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
console.log(end);
// 2:29:59

Javascript comparing two dates has wrong result

I'm trying to learn a little more about JavaScript and decided to make a countdown timer that will show from years all the way down to milliseconds. It's just a learning experiment for me.
The minutes are not correct. If I refresh the browser, the seconds and minutes always start at 59. I think this may be because I am calling the Date object and possibly resetting it. What I am looking for is to count down to a certain date.
Because this is a learning experiment for me, if you see something else that may be improved upon, please let me know.
var dateA = new Date();
var dateB = new Date('June 3, 2014 00:27:00');
var cntr = setInterval(clock, 10);
function clock()
{
dateB = (dateB - 10);
var date = new Date(dateB);
var yrs = Math.abs(date.getUTCFullYear() - dateA.getUTCFullYear() );
var mos = Math.abs(date.getUTCMonth() - dateA.getUTCMonth());
var days = Math.abs(date.getUTCDate() - dateA.getUTCDate());
var hrs = Math.abs(date.getUTCHours() - dateA.getUTCHours());
var mins = Math.abs(date.getUTCMinutes() - dateA.getUTCMinutes());
var secs = Math.ceil(date.getUTCSeconds() - dateA.getUTCSeconds() / 60);
var mill = Math.ceil(date.getUTCMilliseconds() - dateA.getUTCMilliseconds() / 999);
var str =
yrs + ' Years ' +
mos + ' Months ' +
days + ' Days ' +
hrs + ' Hours ' +
mins + ' Mins ' +
secs + ' Secs ' +
mill + ' Mill';
document.getElementById('clock').innerHTML = str;
}
var yrs = Math.abs(date.getUTCFullYear() - dateA.getUTCFullYear() );
var mos = Math.abs(date.getUTCMonth() - dateA.getUTCMonth());
var days = Math.abs(date.getUTCDate() - dateA.getUTCDate());
var hrs = Math.abs(date.getUTCHours() - dateA.getUTCHours());
var mins = Math.abs(date.getUTCMinutes() - dateA.getUTCMinutes());
You cannot just take the absolute value of the differences of each part of the date! You end up with totally wrong numbers.
var secs = Math.ceil(date.getUTCSeconds() - dateA.getUTCSeconds() / 60);
var mill = Math.ceil(date.getUTCMilliseconds() - dateA.getUTCMilliseconds() / 999);
Why would you divide these by 60 and by nearly-1000?!
Instead, to calculate the time difference, you will need to get the complete difference (in milliseconds, usually) and convert that into the different units. Your function should look like this:
var el = document.getElementById('clock');
function clock() {
var diff = dateB - Date.now();
var yrs = Math.floor(diff / 31536000000);
var mos = Math.floor(diff / 2678400000) % 12;
var days = Math.floor(diff / 86400000) % 31;
var hrs = Math.floor(diff / 3600000) % 24;
var mins = Math.floor(diff / 60000) % 60;
var secs = Math.floor(diff / 1000) % 60;
var mill = diff % 1000;
var str =
yrs + ' Years ' +
mos + ' Months ' +
days + ' Days ' +
hrs + ' Hours ' +
mins + ' Mins ' +
secs + ' Secs ' +
mill + ' Mill';
el.innerText = str;
}
If you're using javascript for comparing dates or counting number of days, you might have some problems. You should use a library for better results.
I recommend you to use http://momentjs.com/ for date or time function. It's easy to use and much more flexible.
This should answer your question: Countdown timer using Moment js
try this..
function checkFromDate(sender, args) {
if (sender._selectedDate > new Date()) {
alert("You cannot select a day future than today.");
sender._selectedDate = new Date();
sender._textbox.set_Value(sender._selectedDate.format(sender._format))
}
}

moment.js diff date formatting

I'm using moment.js and want to calculate the difference between two timestamp,format them afterwards and display them in a div.
var diffTime = moment(1390310146.791877).diff( 1390309386.271075);
This gives me 760 seconds, but I want to format it like this:
(days, hrs, mins, secs) and only show days, hours and seconds if they are higher than 0.
How do I achieve that ?
moment.duration should be used
let startTime = moment('09:45:20', 'h:mm:ss A').format("HH:mm:ss");
let endTime = moment('10:30:35', 'h:mm:ss A').format("HH:mm:ss")
var todayDate = moment(new Date()).format("MM-DD-YYYY"); //Can change, based on the requirement
var startDate = new Date(`${todayDate} ${startTime}`);
var endDate = new Date(`${todayDate} ${endTime}`);
var diffTime = moment(endDate).diff(startDate);
var duration = moment.duration(diffTime);
var years = duration.years(),
days = duration.days(),
months = duration.months(),
hrs = duration.hours(),
mins = duration.minutes(),
secs = duration.seconds();
var div = document.createElement('div');
div.innerHTML = years + ' years ' + months + 'months ' + days + ' days ' + hrs + ' hrs ' + mins + ' mins ' + secs + ' sec';
document.body.appendChild(div);
jsfiddle
try this
var diffTime = moment(moment(1390310146.791877).diff( 1390309386.271075)).format('H m s');
it will output "5 30 0"
Edit
here is the simple way to get the difference. for this both the time should be in the same timezone.
var a = moment(1390310146.791877);
var b = moment(1390309386.271075);
a.diff(b)//To get the difference in milliseconds
a.diff(b,'seconds')//To get the difference in seconds
a.diff(b,'minutes')//To get the difference in minutes
a.zone()//Get the timezone offset in minutes
hope this helps.

Why do I get +1 hour when calculating time difference in javascript?

I trying to create a very simple time difference calculation. Just "endtime - starttime". I'm getting +1 hour though. I suspect it has with my timezone to do, since I'm GMT+1.
Regardless, that should not affect the difference, since both start and end times are in the same timezone.
Check my running example-code here:
http://jsfiddle.net/kaze72/Rm3f3/
$(document).ready(function() {
var tid1 = (new Date).getTime();
$("#tid").click(function() {
var nu = (new Date).getTime();
var diff = new Date(nu - tid1);
console.log(diff.getUTCHours() + ":" +
diff.getUTCMinutes() + ":" +
diff.getUTCSeconds());
console.log(diff.toLocaleTimeString());
});
})
You must understand what Date object represent and how it stores dates. Basically each Date is a thin wrapper around the number of milliseconds since 1970 (so called epoch time). By subtracting one date from another you don't get a date: you just get the number of milliseconds between the two.
That being said this line doesn't have much sense:
var diff = new Date(nu - tid1);
What you really need is:
var diffMillis = nu - tid1;
...and then simply extract seconds, minutes, etc.:
var seconds = Math.floor(diffMillis / 1000);
var secondsPart = seconds % 60;
var minutes = Math.floor(seconds / 60);
var minutesPart = minutes % 60;
var hoursPart = Math.floor(minutes / 60);
//...
console.log(hoursPart + ":" + minutesPart + ":" + secondsPart);
Working fiddle.

Calculating time diference in JavaScript (days+hours+minutes+seconds)

lol sorry i posted it accidentally
I'm new to JavaScript and i'm trying to make a simple countdown script that should show the difference between the end date and today's server date.
here is a great example of what i'm trying to do http://moblog.bradleyit.com/2009/06/javascripting-to-find-difference.html
The only thing i want to add is another variable with a calculated seconds. How can i do that?
Here is the code:
var today = new Date();
var Christmas = new Date("12-25-2009");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.round(diffMs / 86400000); // days
var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
alert(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas 2009 =)");
You have two issues with this code:
1: You need to use a date that will be accepted across browsers so it needs to be formatted with / instead of -.
2: You are rounding, which when rounding up will give you inaccurate numbers. All numbers need to be rounded down. Here is a function do do so:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
So your final code should look like this:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
var today = new Date(); // date and time right now
var goLive = new Date("06/01/2013"); // target date
var diffMs = (goLive - today); // milliseconds between now & target date
var diffDays = roundDown(diffMs / 86400000); // days
var diffHrs = roundDown((diffMs % 86400000) / 3600000); // hours
var diffMins = roundDown(((diffMs % 86400000) % 3600000) / 60000); // minutes
var diffSecs = roundDown((((diffMs % 86400000) % 3600000) % 60000) / 1000 ); // seconds
var endDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
var today = Date.now()
var timeLeft = endDate - today // timeLeft would be in milliseconds
// Parse this into months, days, hours, ...
Put this in a function and set it up to be called every second or so using setInterval.
This should get you started with the JavaScript date object and it's associated methods.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Also, look up the setInterval() method, that will allow you to fire code in set intervals (for example, updating the countdown text).

Categories

Resources