Anuradha
Anuradha

Reputation: 53

Add timestamp offset to local timestamp in javascript

Suppose I am in Sri Lanka (offset +5.30). I want to schedule a Meeting at 8.00 AM in American local time(offset -10.00) while I am staying in Sri Lanka. I want to create my timestamp by adding offset of America to my local timestamp. Have any one has idea of how to do that in javascript without using moment timezone. What I have done is,

 var localTimestamp = new Date('2015-02-27 14:59').getTime();
 var offset = parseInt('-10.00')*60*60;
 var timestamp = (localTimestamp/1000) + offset;

Above gives wrong result after converting back to local time.

Upvotes: 1

Views: 461

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075089

There are a couple of issues there.

  1. You're relying on undocumented behavior here:

    var localTimestamp = new Date('2015-02-27 14:59').getTime();
    

    That string format is not defined in the specification. V8 will parse it (as of this writing), but you have no guarantees about whether it parses it in local time or UTC or what, because (again) it's undefined. To create a date/time in a defined way, you could use the date/time format in the spec, but sadly they got that format wrong in ES5 and are having to fix it in ES6: In ES5, the absense of the "Z" at the end was defined as meaning UTC, but that's at odds with the ISO-8601 standard it was based on, and means you don't have a way to say "local time." Since ES6 will fix this, some engines have already changed it; whether your version of V8 has depends on the version number. So you're probably better off using the multi-argument date constructor:

    var localTimestamp = new Date(2015, 1, 27, 14, 59).getTime();
    // Remember that months start at 0 -^
    
  2. There's zero reason for parseInt('-10.00'); just use -10.

  3. Here you're dividing by 1000:

    var timestamp = (localTimestamp/1000) + offset;
    

    But then you say

    Above gives wrong result after converting back to local time.

    You need to multiply again when going back:

    var newDate = new Date(timestamp * 1000);
    
  4. Then you need to be careful about how you use the resulting Date, because it still works in what it considers local time. But if you're converting it to a string, etc., you could use it.

Upvotes: 1

Related Questions