Moment.js duration days error - javascript

I'm doing a count down with moment.js and duration to return days, hours, minutes and seconds. So, when I use moment.duration with miliseconds, it return a non-sense days...
var miliseconds = 4423852000
var divided = miliseconds / 1000 / 24 / 3600 // return: 51,20 days (correct)
var duration = moment.duration(miliseconds).days() // return: 20 days (???)
document.querySelector('.days').innerHTML = divided
document.querySelector('.result').innerHTML = duration
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.js"></script>
<pre class="days"></pre>
<pre class="result"></pre>
I'm using moment.duration correctly??

You should use asDays() instead of day():
As with the other getters for durations, moment.duration().days() gets the days (0 - 30).
moment.duration().asDays() gets the length of the duration in days.
var miliseconds = 4423852000
var divided = miliseconds / 1000 / 24 / 3600
var duration = moment.duration(miliseconds).asDays()
document.querySelector('.days').innerHTML = divided
document.querySelector('.result').innerHTML = duration
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.js"></script>
<pre class="days"></pre>
<pre class="result"></pre>

Related

change days and hours by how time flies

I am getting the elapsed time in minutes, hours and days, between two dates, a past date and the current one, I already get this data, but I want this data to change as the minutes, days and hours increase. For example, when I get to 60 minutes, the time changes to 1 hour and the minutes go to 0, when 24 hours go by, these hours change to a day and the hours go back to 0, and so on, the data I get keeps increasing , how can I do this?
const calculateDate = () => {
const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();
const minutes= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / 60);
const hours= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / (3600));
const days= Math.floor((currentDate.getTime() - date.getTime()) / (1000*60*60*24));
}
With this, get the minutes, hours and days, but how would you update so that when you reach 60 minutes it goes to one hour and 24 hours to one day?
The JavaScript Date object has built in functions for what you want to do.
var now = new Date()
var h = now.getHours()
var m = now.getMinutes()
var s = now.getSeconds()
The new Date created in above example is set to the time it was created.
You can get the current time using the Date object itself:
var current = Date()
With your method you always see the full duration just in a different unit.
You have to use the modulo operator to get only the "missing part" (the remainder of the division) to the next unit:
const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();
const dateDiff = (currentDate.getTime() - date.getTime()) / 1000;
const seconds = Math.floor(dateDiff) % 60;
const minutes = Math.floor(dateDiff / 60) % 60;
const hours = Math.floor(dateDiff / (60 * 60)) % 24;
const days = Math.floor(dateDiff / (60 * 60 * 24));

how to get the duration from two dates in the following format

var date2 = new Date("04/14/2022 12:49:29")
var date1 = new Date("04/09/2022 06:16:49")
I want to get the following duration ("126:32:40 ")
Try this solution.
Step - 1. Get the time difference between both date
const date1 = new Date("04/09/2022 06:16:49");
const date2 = new Date("04/14/2022 12:49:29");
const diff = date2.getTime() - date1.getTime();
console.log(diff); // Will display 455560000 i.e miliseconds
Step - 2 Convert milliseconds to seconds
let seconds = diff / 1000; // Will return seconds
Step - 3 Convert seconds to Hours
const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
seconds = seconds % 3600;
Step - 4 Convert Seconds to miniutes
const minutes = parseInt( seconds / 60 );
seconds = seconds % 60;
console.log(hours+":"+minutes+":"+seconds)

how much time is passed from a certain event

Need to show an info - how much time is passed from a certain event.
For example:
var event = '2017-04-25 09:20:00';
var datea = new Date(event);
var dateb = new Date();
var diff = Math.abs(dateb.getTime() - datea.getTime());
var days = Math.ceil(diff / (1000 * 3600 * 24));
var hours = Math.ceil(diff / (1000 * 3600));
var mins = Math.ceil(diff / (1000 * 60));
var sec = Math.ceil(diff / (1000));
But this are all total values of days, hours... etc.
I want to show the info this way:
THE EVENT HAPPENS xYears xMonths xDays xHours xMins xSecs AGO
How to calculate and display the info in the above way?
Years and Months may be rounded on 365 and 30 days.
Also the info should be updated on each second.
Any help?
Using moment.js, which is the most reliable date library I know, it would look like this:
// your date
var event = '2017-04-25 09:20:00';
// Moment objects to compare
var datea = moment(event,"YYYY-MM-DD HH:mm:ss");
var now = moment();
// Find the difference
var diff = now.diff(datea);
var d = moment.duration(diff);
// Resulting object
console.log(d._data);
// Formatting...
$("span").html(d._data.years+" years, "+
d._data.months+" months, "+
d._data.days+" days, "+
d._data.hours+" hours, "+
d._data.minutes+" minutes, "+
d._data.seconds+" seconds");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<span></span>
Look for these moment methods:
parsing formats
duration
difference

how to get the days and exact minutes,exact hours from two dates in javascript?

I have start date time and end time,i need to split how many days , hours ,minutes in the two dates
for example ,
startdatetime = "09-06-2017 10:30"
enddatetime = "10-06-2017 11:45"
i need this result : 1 day 1 hour and 15 minutes
I try this one
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
console.log(a);
var hours = Math.trunc(a/60);
var minutes = a % 60;
var one_day=1000*60*60*24
var days = Math.ceil(a/one_day)
var time = [hours,minutes,days];
return time;
}
i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance
Using momentjs, you can :
Parse your input string using moment(String, String)
Parse your input string using moment.utc
Get difference using diff() function
Create a duration from the difference value
Use duration days(), hours(), minutes() to get your result
Here a live sample:
var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.days() + ' days ' + dur.hours() + ' hour ' + dur.minutes() + ' minutes');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
If you want you can use moment-duration-format plug-in to get the same result using format() method on duration. Here a working sample:
var startdatetime = "2017-06-09T07:00:01.000Z";
var enddatetime = "2017-06-10T09:00:00.000Z";
// Parse input
var mStart = moment.utc(startdatetime);
var mEnd = moment.utc(enddatetime);
// Calculate difference and create duration
var dur = moment.duration( mEnd.diff(mStart) );
// Show the result
console.log(dur.format('d [day] h [hour] m [minutes]'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
Well, if you look at documentation for javascript Date objects, there is a getTime() method . You can also use the valueOf() method. They both return the number of milliseconds representing your Date object.
You can simply call that on both Date objects and then find the difference. Once you have the difference you can find the amount of secs, mins , hrs, days, etc. Here is an example:
var start = new Date(*some date*);
var end = new Date(*some date*);
var dif = end.valueOf() - start.valueOf();
if (dif >= 0) {
var secs = Math.floor(dif / 1000 % 60);
var mins = Math.floor(dif / 1000 / 60 % 60);
var hrs = Math.floor(dif / 1000 / 60 / 60 % 24);
var days =
Math.floor(dif / 1000 / 60 / 60 / 24 % 365);
var yrs =
Math.floor(dif / 1000 / 60 / 60 / 24 / 365);
Try the following:
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(minutes)
{
var hours = (minutes / 60 | 0) % 24;
var minutes = (minutes | 0) % 60;
var days = minutes / 60 / 24 | 0;
return [hours, minutes, days];
}
Note that in javascript, doing x | 0 is the same as Math.floor(x).
It looks to me like your calculation for hours still has the days in it. Once you have established the days, just subtract those out when you calculate the hours.
var start = new Date("June 09, 2017 10:30:00");
var end = new Date("June 10, 2017 11:45:00");
var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
console.log(time);
function display(a)
{
var minutes = a % 60;
var one_day=1000*60*60*24
var days = Math.ceil(a/one_day)
var hours = Math.trunc((a-(days*1440))/60);
var time = [hours,minutes,days];
return time;
}
Having said that, I highly recommend moment.js to handle this type of thing, if you can.
var startDateTime = 1497029400000;
var endDateTime = 1497120300000;
var timeDifference = endDateTime - startDateTime
// with the given dates, days equals 1.0520833333333333
// we want to extract the trailing decimal values using modulus to get the other times
function getTimeDifference(timeDifference) {
var days = timeDifference/1000/60/60/24
days >= 1
? var dayCount = Math.trunc(days); // store the day count
: var dayCount = 0; // it is less than one day
// get the remaining hours
var hours = (days % 1) * 24;
var hoursCount = Math.trunc((days % 1) * 24);
// get the remaining minutes
var minutesCount = Math.ceil((hours % 1) * 60);
}

JavaScript (Jquery) Decimal Point Removal

Currently I am working on JavaScript, jQuery, HTML5 to improve myself. I have a opensourcely coded clock, which I have converted it into a counter (reverse counter).
Problem I am having is, in my setInterval(){...} I have four variables -> second,min,hour, and day. The problem is, when I get the seconds, I get something like 1.155, 2.312, 3.412 (seconds).
My setInterval function is below
setInterval(function(){
//var duration = parseInt(Date.now() /1000 ) - 1365470000;
var futureTime = Date.parse('April 10, 2013 22:00:00');
var duration = (( parseInt(Date.now() - futureTime ) / 1000));
var seconds = duration % 60;
duration = parseInt(duration / 60);
var minutes = duration % 60;
duration = parseInt(duration / 60);
var hours = (duration)%24;
duration = parseInt(duration / 24);
var days = duration % 365;
animation(gVars.green, seconds, 60);
animation(gVars.blue, minutes, 60);
animation(gVars.orange, hours, 24);
animation(gVars.red, days, 365);
},1000);
}
And my output is below for some random time since i use parseInt(Date.now()).
I have to give the link since I don't have enough rep.
http://i.stack.imgur.com/0Zkbi.png
How can I get rid of the decimal point in setInterval(){} functions?
Thanks in advance.
JavaScript offers more convinient API to work with date and time in order to fetch seconds, minutes, hours and days. Try this code:
var duration,
seconds,
minutes,
hours;
duration = new Date((new Date('April 11, 2013 23:00:00')) - (new Date()));
seconds = duration.getSeconds();
minutes = duration.getMinutes();
hours = duration.getHours();
Now you will have integer values in all 4 variables above, without any decimal point.
var seconds = 1234.13;
var seconds = seconds + '';
seconds = seconds.split('.')[0];
console.log(seconds);

Categories