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.
Related
I am trying to calculate the difference between two timestamp
"2020-03-18T17:34:45.856Z", "2020-03-18T16:34:45.856Z"
the difference should be like this: 2 hours 20min 30sec
I have tried using
return moment.utc(moment(startDate, 'HH:mm:ss').diff(moment(endDate, 'HH:mm:ss'))).format('HH:mm:ss');
m not sure how to get the desired format
You need to get it manually using Moment Duration
const startDate = "2020-03-18T17:34:45.856Z";
const endDate = "2020-03-18T16:34:45.856Z";
const diff = moment(startDate).diff(moment(endDate));
const duration = moment.duration(diff);
const hrs = duration.hours();
const mins = duration.minutes();
const secs = duration.seconds();
console.log(hrs + "hours " + mins + "min " + secs + "sec");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
i try to disply time with the showing AM / PM format but i am unable to find any code can you please guide me
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
document.getElementById("dt").innerHTML = time;
<p id='dt'></p>
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds()+" ";
time+= dt.getHours()>=12?"PM":"AM"
document.getElementById("dt").innerHTML = time;
<div id="dt"></div>
Just check if the value less than 12, and keep the hours under 12 and return 12 instead of 0 by: (hours %12 || 12):
var dt = new Date();
var time = (dt.getHours()%12||12) + ":" + dt.getMinutes() + ":" + dt.getSeconds() + " " + (dt.getHours() < 12)===0?"AM" : "PM";
document.getElementById("dt").innerHTML = time;
Just compare the hours to if its less than 12 and if so set a variable to either AM or PM. Note that the following has the leading 0 added to the mins and secs if required (the slice will only include the 0 if the length of the value is 1).
var dt = new Date();
var hrs = dt.getHours();
var hours = hrs % 12;
var mins = '0' + dt.getMinutes();
var minutes = mins.slice(-2);
var secs = '0' + dt.getSeconds();
var seconds = secs.slice(-2);
var amPm = hrs< 12 ? 'AM' : 'PM';
var time = hours + ":" + minutes + ":" + seconds + ' ' + amPm;
document.getElementById("dt").innerHTML = time;
<p id = "dt"></p>
For auction web app I want to run a timer after getting time from firebase-database, how to decrease time by one second using setInterval() in ReactJS
I tried below code that is increasing time but I want decrease
function display()
{
var today = new Date();
var month = today.getMonth();
var day = today.getDay();
var year = today.getFullYear();
var hour = today.getHours() > 12 ? today.getHours() - 12 : today.getHours();
var minute = today.getMinutes();
var seconds = today.getSeconds();
var output = month + '/' + day + '/' + year + ' - ' +
hour + ':' + minute + ':' + seconds + ':';
console.log(output)
}
var timer = setInterval(display,1000)
console.log(timer)
You need to compare against some time when working with setInterval in this fashion. The time returned from the server is perfect for this. The psuedo-code is provided
setInterval(function() {
var difference = timeFromServer - Date.now();
console.log(formatDate(difference));
}, 1000);
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.
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))
}
}