Programmeur
Programmeur

Reputation: 1531

javascript: convert seconds to months

I am using the following script to do a countdown.

function startCountdown() {
    var countdownDate = new Date("9/13/2013 12:00 AM");
    var currentDate = new Date();
    var dateDifference = new Date(countdownDate - currentDate);
    var seconds = dateDifference.valueOf() / 1000;
    CountBack(seconds);
}

function CountBack(seconds) {
    var DisplayFormat = "DAYS days and HOURS hours";
    DisplayFormat = DisplayFormat.replace("DAYS", (Math.floor(seconds/86400)) % 100000);
    DisplayFormat = DisplayFormat.replace("HOURS", (Math.floor(seconds/3600)) % 24);
    $('span.countdown').html(DisplayFormat);
}

startCountdown();

How can I show the months left too? (I want like: 3 months, 29 days and 3 hours)

Thank you.

Upvotes: 2

Views: 4660

Answers (2)

Ahmad Bakr
Ahmad Bakr

Reputation: 1

function ageInTime(theAge) {
    if (theAge < 100 && theAge > 10)  {
        console.log(`${theAge} Years
        ${theAge * 12} Months
        ${theAge * 12 * 4} Weeks
        ${theAge * 12 * 4 * 7} Days
        ${theAge * 12 * 4 * 7 * 24} Hours
        ${theAge * 12 * 4 * 7 * 24 * 60} Minuts
        ${theAge * 12 * 4 * 7 * 24 * 60} Seconds`)
    } else {
        console.log("Age Out Of Range")
    }
}

ageInTime(110); 
ageInTime(38);

Upvotes: 0

flavian
flavian

Reputation: 28511

Use this simple nice function. Check out the LIVE DEMO:

var cc = new Date("9/13/2012 12:00 AM"),
    c = new Date();

function timeDifference(d, dd) {
    var hour = 60 * 60 * 1000,
        day = hour * 24,
        month = day * 30,
        ms = Math.abs(d - dd),
        months = parseInt(ms / month, 10);    

    ms = ms - months * month;    
    var days = parseInt(ms / day, 10); 
    ms -= days * day;
    var hours = parseInt(ms / hour, 10);   
    ms -= hours * hour;

    return [
        months + " months",
        days + " days",
        hours + " hours"
    ].join(", ");
};

document.body.innerHTML += timeDifference(cc, c) + "<br />";

Upvotes: 5

Related Questions