简体   繁体   中英

How to get date and time using moment for a given timezone offset

{
    "time": 1627375726.8367202,
    "tzoffset": -25200,
    "ok": 1
}

Using above JSON I need to get date, time and timezone. I have tried many ways but could not succeed. Is there a way to get date, time and timezone. I am using JavaScript.

Thanks,

Check out there Documentation

A Little Example is here

moment.parseZone("2013-01-01T00:00:00-13:00").utcOffset(); // -780 ("-13:00" in total minutes)

We can use your specified unix time and offset to get the current date and time using the moment.utcOffset function. We have to divide your tzoffset by 60, since it is (presumably) in seconds whereas moment expects minutes.

It's usually not possible to get a unique timezone value, since your tzoffset is going to be shared by multiple zones, the best we can do is get a list of these:

 const input = { "time": 1627375726.8367202, "tzoffset": -25200, "ok": 1 }; console.log("UTC time:", moment.unix(input.time).utc().format('YYYY-MM-DD HH:mm')) console.log("Time in Timezone:", moment.unix(input.time).utcOffset(input.tzoffset / 60).format('YYYY-MM-DD HH:mm')) console.log("Time in Timezone (with offset):", moment.unix(input.time).utcOffset(input.tzoffset / 60).format()) console.log("Possible timezones:", getPossibleTimezones(input.time, input.tzoffset)) function getPossibleTimezones(time, tzoffset) { return moment.tz.names().filter(zone => moment.tz(moment.unix(time), zone).utcOffset() === input.tzoffset / 60); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" referrerpolicy="no-referrer"></script> <script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

I'd also consider using luxon since moment is now in maintenance.

We can use the FixedOffsetZone to get local time in that zone:

 const input = { "time": 1627375726.8367202, "tzoffset": -25200, "ok": 1 }; let { DateTime, FixedOffsetZone } = luxon; let zone = new FixedOffsetZone(input.tzoffset / 60) console.log("UTC time:", DateTime.fromSeconds(input.time, { zone: 'UTC' }).toISO()) console.log("Time in timezone:", DateTime.fromSeconds(input.time, { zone: zone }).toISO())
 <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.0.1/luxon.min.js" integrity="sha512-bI2nHaBnCCpELzO7o0RB58ULEQuWW9HRXP/qyxg/u6WakLJb6wz0nVR9dy0bdKKGo0qOBa3s8v9FGv54Mbp3aA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM