Jim
Jim

Reputation: 2322

How to parse moment into specific timezone from moment.unix()

I have an initial value for a timestamp (created in User-1's timezone) I'm retrieving from firebase's firestore. the format this is in, is seconds in UTC from the Unix Epoch.

My goal is to take the initial timestamp value, and convert it to the timezone of the current user. if I use

moment.unix(initial_In_Seconds).format("H:mma") I get the correct initial time. Using .unix() is the only way I've been able to get the correct initial time. Now I need to convert it to a specific timezone. lets say "America/Denver" (the initial timezone is GMT -05:00)

I haven't been successful using moment.tz() in any of my amalgamations thus far.

I've tried:

moment.tz(moment.unix(initial_In_Seconds).format("H:mma"), "America/Denver")

let unix = moment.unix(initial_In_Seconds).format("H:mma");
let parsed = moment.tz(unix, "America/Denver");

How can this be parsed? Moment.js confuses me

Upvotes: 0

Views: 999

Answers (2)

RobG
RobG

Reputation: 147403

If your timezone offset is specified using IANA representative locations, such as 'America/Denver', then you can likely use toLocaleString provided the locations aren't too obscure (i.e. aren't unsupported by ECMAScript implementations likely to run your code), e.g.

function timeValueWithTimezone(unixOffset, loc) {
  let d = new Date(unixOffset * 1000);
  return d.toLocaleString(void 0, {
    hour12: true,
    hour: 'numeric',
    minute: '2-digit',
    timeZone: loc
  });
}

let timeValue = 1582090120;
let loc = 'America/Denver';

console.log('At your local time: ' +
  new Date(timeValue * 1000).toLocaleString(void 0, {
    hour12: true, 
    hour: 'numeric', 
    minute: '2-digit'
}));
console.log('Denver local time is: ' + timeValueWithTimezone(timeValue, loc));

Upvotes: 1

Jim
Jim

Reputation: 2322

further playing has yielded better results:

moment
 .tz(moment.unix(props.navigation.state.params.time.start.seconds),'America/Denver')
 .format('H:mma')

unfortunately for hours that are PM, it gives military time...and im interested in 12hr format...

EDIT: changes -> .format('h:mma') yields 12hr format

Upvotes: 0

Related Questions