-2

I have the follow function that properly returns the date in the format required, but the value returned isn't respecting the local timezone. In this case, its 4 hours off. What would I need to modify in this function to make it add the proper offsets based on the users location?

Thanks!

function date_str(seconds) {
    var dt = new Date(1970, 0, 1);
    dt.setSeconds(seconds);
    console.log(dt);
    var month = dt.getMonth() + 1;
    var date = dt.getDate();
    var year = dt.getFullYear();
    var hours = dt.getHours();
    var minutes = dt.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    return month + '/' + date + '/' + year + ', ' + hours + ':' + minutes + ' ' + ampm;
}

Edit: Passing unix time to function 1396450616.505 which converts to Wed, 02 Apr 2014 14:56:56 GMT which returns Sent at 4/2/2014, 2:56 PM from the function itself. The time here is 10:56 AM EST.

Ray
  • 82
  • 7
  • Could you post a current date example along with your current date and time and the results you got from the function? Also, list your timezone please. – SparoHawk Apr 02 '14 at 14:36
  • http://stackoverflow.com/questions/439630/how-do-you-create-a-javascript-date-object-with-a-set-timezone-without-using-a-s Google before you ask – weeknie Apr 02 '14 at 14:41
  • Passing unix time to function `1396450616.505` which converts to `Wed, 02 Apr 2014 14:56:56 GMT` which returns `Sent at 4/2/2014, 2:56 PM` from the function itself. The time here is 10:56 AM EST. Weeknie, I saw that post before. Changing the code above to `var dt = new Date(Date.UTC(1970, 0, 1));` gets it closer, but its still an hour off, in this case changes to 9:56 AM. Thanks guys – Ray Apr 02 '14 at 15:00

1 Answers1

1

Assuming that seconds is a unix epoch (UTC), you should just use

function date_str(seconds) {
    var dt = new Date(seconds*1000);
    console.log(dt);
    …

instead. The get…() methods will respect the local timezone. If you don't want that, you should use the getUTC…() equivalents.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375