ankitjain11
ankitjain11

Reputation: 253

How do I save date/time in some other timezone

I need to save a Date: February 16th, 2017 5PM HST.

The database (Parse) only accepts JS Date. And, my system timezone is IST. JS Date does not have the ability to save in a different timezone.

To overcome this, I save three variables. Date (Calculated, calculation explained below), Timezone Offset, Timezone

Date is converted using moment.tz(DateObject, Timezone).

But, calling the toDate() function, seems to change it back to IST.

On further examination, I found a _d key to the Moment object, which seems to have the converted datetime in IST.

But, I seem to cannot get it to work.

Any hints would be helpful.

Upvotes: 0

Views: 194

Answers (3)

Birchlabs
Birchlabs

Reputation: 8056

What do you mean by "save in a different timezone"? Timezone is a presentation-layer concern. 01:00+00:00 and 02:00-01:00 are the same time, presented differently. The point in time is represented using a large integer (the timestamp), and this timestamp is the thing you should save.

When you load this timestamp and want to use it again: you can present it from the perspective of any zone you choose.

//-- parsing the user input...

// parse HST (Honolulu Standard Time) date-time
var inputTime = moment.tz("February 16th, 2017 5PM", "MMMM Do, YYYY hA", "Pacific/Honolulu");

// in case you want to double-check that it parsed correctly
var inputTimePrettyPrinted = inputTime.format(); // "2017-02-16T17:00:00-10:00"

// grab timestamp
var timestamp = +inputTime;

//-- presenting the stored timestamp in Indian Standard Time...

// install a timezone definition for Indian Standard Time
moment.tz.add("Asia/Calcutta|HMT BURT IST IST|-5R.k -6u -5u -6u|01232|-18LFR.k 1unn.k HB0 7zX0");
moment.tz.link("Asia/Calcutta|Asia/Kolkata");

var timePresentedInIndianTime = moment(timestamp).tz("Asia/Calcutta");

var indianTimePrettyPrinted = timePresentedInIndianTime.format(); // "2017-02-17T08:30:00+05:30"

Upvotes: 2

Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6887

You need to use moment tz to add to HST

var now = new Date();
moment.tz.add('HST|HST|a0|0|');
console.clear();
var converted = moment(now).tz("HST").format();
console.log(now);

console.log(converted);

Here is the jsfiddle link

Check console.log for the answer.

Fri Feb 17 2017 18:24:49 GMT+0530 (India Standard Time) //IST time
2017-02-17T02:54:49-10:00 // HST Time

Upvotes: 0

Akash Thakkar
Akash Thakkar

Reputation: 83

Try something like this:

var UTC = new Date();
var UTC = UTC.getTime() // Get UTC Timestamp

var IST = new Date(date); // Clone UTC Timestamp
IST.setHours(IST.getHours() + 5); // set Hours to 5 hours later
IST.setMinutes(IST.getMinutes() + 30); // set Minutes to be 30 minutes later

var EST = new Date(date); // Clone date
EST.setHours(EST.getHours() - 4); // set EST to be 4 hour earlier

You can change according to your need.

Upvotes: 0

Related Questions