Setting Date() object to specific time if I know the timezone in string

Viewed 279

I am trying to do something in node.js

So now if a user inputs a date, example 21/10/2020 at 1pm, I would like to create a Date() object with that date but adjusted to the User's timezone. The only information I have about the timezone is the IANA(?) name, such as "Asia/Shanghai"

so is there anyway to do something like

const adjusted = new Date(2020, 9, 21, 13, 0, 'Asia/Shanghai');

to get the correct date? I am open to using packages.

Edit: Similarly, is there any easy packages out there to find the time offset (e.g. UTC + x) given the name? For example it would return +8 if the input is 'Asia/Shanghai'

Edit 2: To anyone else who came upon this, you can do what I want using dayjs. for example, dayjs.tz("2020-12-01 12:30", "Europe/London") would give you a dayjs object with the correct time stamp.

2 Answers

You can use moment-timezone to create a date with a certain timezone:

const date = moment().tz("Asia/Shanghai");
console.log(date.format());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>

That's a great answer from @eol.

I'd also consider giving the new Luxon module a look, it does a lot of this kind of thing very nicely and it has an IANAZone class too!

const timeZone = "Asia/Shanghai";
const DateTime = luxon.DateTime;
const dt = DateTime.fromObject( { year: 2020, month: 10, day: 21, hour: 13, zone: timeZone})
console.log(`Time (${timeZone}):`, dt.toString());
console.log(`Time (UTC):`, dt.toUTC().toString());
const IANAZone = luxon.IANAZone;
let zone = IANAZone.create(timeZone);
console.log("UTC Offset:", (zone.offset(dt) >=0 ? "+": "-") + (zone.offset(dt) / 60));
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.25.0/luxon.min.js" integrity="sha512-OyrI249ZRX2hY/1CAD+edQR90flhuXqYqjNYFJAiflsKsMxpUYg5kbDDAVA8Vp0HMlPG/aAl1tFASi1h4eRoQw==" crossorigin="anonymous"></script>

Related