0

I've a custom binding handler that returns the time of a given date:

var item = allBindings().data;

var dateInit = new Date(item.Fecha());

var timezone = 0; //dateInit.getTimezoneOffset() * 60000;

var ticksInit = dateInit.getTime() + timezone;
var duration = item.Duracion() * 60 * 1000;
var ticksEnd = ticksInit + duration;

var hourInit = getShortTime(new Date(ticksInit));
var hourEnd = getShortTime(new Date(ticksEnd));

item.Fecha() is a observable that contains the date on JSON Format : '2015-10-20T12:00:00' in this case

On a Windows browser ticksInit has a value of 1445335200000 but on an Ipad it has the value 1445342400000.

The difference is just two hour, it seems like Ipad is applying a timezone corrector.

  • 6
    You should **never** parse strings using the Date constructor, manually parse it using [*your own parser*](http://stackoverflow.com/questions/15517024/how-to-assume-local-time-zone-when-parsing-iso-8601-date-string) or a well maintained library. In ES5, ISO-like formats without a timezone are treated as UTC, in ECMAScript 2015 they are treated as local (and in previous versions were implementation dependent). That would explain the difference being equal to the timezone offset. Also, IE8 will return NaN (it won't natively parse ISO formats). – RobG Oct 20 '15 at 08:37
  • This would be a lot easier with [moment.js](http://momentjs.com). Also, it's good you commented out the time zone, because adding ticks to a date is not the right way to compensate for time zone offset. – Matt Johnson-Pint Oct 20 '15 at 16:02

1 Answers1

0

Based on @RobG 's comment here is the code that resolve the problem:

var item = allBindings().data;

var aDate = item.Fecha().split("T")[0].split("-");
var aTime = item.Fecha().split("T")[1].split(":");

var dateInit = new Date(aDate[0],aDate[1]-1,aDate[2],aTime[0],aTime[1]);

//var timezone = 0; //dateInit.getTimezoneOffset() * 60000;

var ticksInit = dateInit.getTime();
var duration = item.Duracion() * 60 * 1000;
var ticksEnd = ticksInit + duration;

var hourInit = getShortTime(new Date(ticksInit));
var hourEnd = getShortTime(new Date(ticksEnd));

$(element).html(hourInit + "-" + hourEnd);
  • 1
    Simpler to get the parts as either `item.Fecha().split(/\D+/)` or `item.Fecha().match(/\d+/g)`. You seem to be ignoring the seconds part of the time. – RobG Oct 20 '15 at 11:35