Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Seconds into Year, Month, Days, Hours, Minutes respectively?

Tags:

javascript

I implemented this logic where I am getting difference between 2 dates and times from Moment.js as seconds, and I need to convert these seconds into 1 Year 3 Months 10 Days 5 Hours 45 Minutes format.

var numyears = Math.floor(seconds / 31536000);
var nummonths = Math.floor((seconds % 31536000) / 2628000);
var numdays = Math.floor(((seconds % 31536000) % 2628000) / 86400);
var numhours = Math.floor((((seconds % 31536000) % 2628000) % 86400)/3600);
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);

I am getting the correct values up to days, but it's having problem from hours onwards.

like image 383
Chanky Mallick Avatar asked Nov 27 '25 01:11

Chanky Mallick


2 Answers

Dates and calendars are political, and don't always match up to simple arithmetic. Most languages that I have worked in solve this problem for you, and to my knowledge, JavaScript does this. (Note that we will have another leap second added to our calendar on June 30, 2015 - http://en.wikipedia.org/wiki/Leap_second.)

Given all of that, this answer is very much an approximation, as it does not take into account lengths of months, leap days, or leap seconds. But, it is something:

var x = new Date('2015-02-26 12:32:54-0600'); // or if you have milliseconds, use that instead
var y = new Date('2015-03-19 01:22:09-0600');
var z = new Date(y-z);
z;
// returns "Wed Jan 21 1970 06:49:15 GMT-0600 (CST)"
// now compare this with epoch
var epoch = new Date('1970-01-01 00:00:00-0600');
var diff_years = z.getYear() - epoch.getYear();
var diff_month = z.getMonth() - epoch.getMonth();
var diff_days = z.getDate() - epoch.getDate();
var diff_hours = z.getHours() - epoch.getHours();
var diff_minutes = z.getMinutes() - epoch.getMinutes();
like image 123
Jason Crickmer Avatar answered Nov 29 '25 17:11

Jason Crickmer


function getDateDiff(expires_in) {
let result = {
    years_diff: 0,
    months_diff: 0,
    days_diff: 0,
    hours_diff: 0,
}
if (expires_in) {
    result.years_diff = Math.floor(expires_in / 31536000);
    result.months_diff = Math.floor((expires_in % 31536000) / 2628000);
    result.days_diff = Math.floor(((expires_in % 31536000) % 2628000) / 86400);
    result.hours_diff = Math.floor((((expires_in % 31536000) % 2628000) % 86400) / 3600);
}
return result }

Here's how i approached this, running some unit tests i discovered that @Aun Shanbaz Awan solution gives wrong hours difference

like image 26
Ahmed Dghaies Avatar answered Nov 29 '25 15:11

Ahmed Dghaies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!