Ad

JavaScript $.datepicker.formatDate With Offset?

- 1 answer

I've managed to hack together some JavaScript to get my dates appearing the way I want:

$(document).ready(function () {
    $('span.date').each(function() { 
        var dateFormat = $(this).text()
        var dateFormat = $.datepicker.formatDate('dd-M-yy', new Date(dateFormat));
        $(this).html(dateFormat + "<br>");
    });
});

However it currently displays the date 1 day in the past. Google tells me this is due to the timezone offset / date being set as UTC in my database with no timezone (date field only, time not important).

From what I can tell, I require an offset for the Date(), but I can't figure out for the life of me how to do so with this current layout.

I have a jsfiddle here: http://jsfiddle.net/ytaLvp5y/

As can be seen in the jsfiddle, the date of "2015-12-31" shows up as "30-Dec-2015" when using "dd-M-yy" format.

Some examples I found on StackExchange of what I have tried (bear in mind I have pretty much no JavaScript experience):

d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );

as well as

var dateFormat = $.datepicker.formatDate('dd-M-yy', new Date(dateFormat)*60*1000);

And many similar variations in between, none of which seem to work (all of them strip the date format all together or produce NaN-undefined-NaN). I think I'm on the right track with the NaN-undefined-NaN). I think I'm on the right track with the TimezoneOffset()*60*1000, I just can't figure out where it goes.

Is anyone able to help point me in the right direction? Thanks in advanced for any responses!

Ad

Answer

First you get a UTC Date object

var date = new Date("2015-12-31");

Next find the offset for your local TZ

var offset = date.getTimezoneOffset() * 60 * 1000; // milliseconds

Now add that to the millisecond representation for the original date and make a new Date.

var myDate = new Date(date.getTime() + offset);

Then apply format

$.datepicker.formatDate("dd-M-yy", myDate);
Ad
source: stackoverflow.com
Ad