Question

I have made a small code snippet. To tell you how old you are, to the second.

But I have found something strange. I know that time and timezones are a nightmare to work with, but this is within my own country and timezone, so I am a little confused.

If I enter the date. 27-12-2013(dd-MM-yyyy), it will show:

Right time

Which is correct. as the time here is: 08:42. The getTimezoneOffset() is -60

But if I go back a day it will show this:

Wrong time

It added an hour!? This is the only date it happens at, and I'm a little confused, because daylight savings time is only applied in spring and fall. The getTimezoneOffset() is ALSO -60

Hope you can shed some light on this.

Timezone: http://www.timezoneconverter.com/cgi-bin/zoneinfo?s=standard&tz=Europe/Copenhagen Javascript: GMT+0100 (Romance Standard Time)
Country: Denmark
JSFiddle: http://jsfiddle.net/d6kBJ/4/

var $output = $(".js-ageoutput");
var bd = new Date(2000, 0, 01);
bd.setHours(0);
bd.setMinutes(0);
bd.setSeconds(0);

function showTotalAge() {
    var ageDifMs = Date.now() - bd.getTime();
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    displayAge(ageDate)
    loopAge();
}

function displayAge(age) {
    var yearOld = Math.abs(age.getFullYear() - 1970);
    var months = age.getMonth();
    var days = age.getDate() - 1;
    var h = age.getHours() - 1;
    var m = age.getMinutes();
    var s = age.getSeconds();
    $output.html(yearOld + ' years <br/>' + months + ' months <br/>' + days + ' days <br/>' + h + 'hours <br/>' + m + ' minutes <br/>' + s + ' seconds<br/>');
}

function loopAge() {
    setTimeout(showTotalAge, 1000);
}
loopAge();

$(".js-birthday").change(function () {
    var vArr = $(this).val().split('-');
    bd = new Date(vArr[0], parseInt(vArr[1], 10) - 1, vArr[2]);
    bd.setHours(0);
    bd.setMinutes(0);
    bd.setSeconds(0);
    console.log(bd);
});
Was it helpful?

Solution

After a deeper inspection of your code, here's your mistake:

var ageDate = new Date(ageDifMs);

The point is: never create a Date object out of a difference of dates, because it would make no sense. What you get is a Date object that represents the instant ageDifMs milliseconds after January 1st, 1970 UTC, and that's what methods like getMonth, getDate, getHours and so on refer to.

So, you got a date like March 28th, 1970 and that's when the Daylight Saving Time happens.

If you want to know the difference of two dates in terms of months and days and so on, you either can compute the differences of the results of getMonth and the other methods, or fix the length of a year, a month and compute the single values using modulus and divisions.

Also, you would rather use setInterval instead of setTimeout for timed continuous tasks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top