datetime-local allows user to enter both a date and a time and the user’s local time zone is used. For simplicity, Let’s enhance this to allow user to select any timezone. We are going to use Moment-Timezone library.
Here is the HTML code for user input of datetime and timezone:
Moment Js Get Local Timezone Offset
- You can use moment.utc since your input is an UTC string. You can use tz to convert your moment object to a given timezone. Please note that the tz function converts moment object to a given zone, while you are using moment.tz parsing function that builds a new moment object with the given zone.
- Moment js convert to local timezone. Moment Timezone, To convert UTC time to Local you have to use moment.local. For more info see docs. Example: var date = moment.utc.format('YYYY-MM-DD I use the Moment.js and Moment-Timezone frameworks, and have a Moment.js date object which is explicitly in UTC timezone.
- Native time zone and Intl support (no locale or tz files). General documentation; API docs; Install guide; Quick tour; For Moment users; Why does.
To get different datetime results, the following code is used:
Get Timezone List
In above HTML code,
dropdownTimeZone will have a list of time-zones. To bind timezone names, we will use moment-timezone library. Let’s add the library files in head tag.
You can use CDN version:
Add a script tag before </body> and add following code to get timezone names:
It will add all timezone as options in dropdownTimeZone and local browser timezone is selected by default.
To load current datetime as default value in HTML5 datetime-local control:
Let’s create a common format to see different dates:
We will use it before displaying the date.
Here are the methods to get UTC, user selected datetime with timezone and its UTC value:
Let’s implement submitDate method which is called on Calculate button click:
As we are loading current date time and browser timezone by default, let’s call submitDate to get results by default.
When you run the page, you will get following datetimes
and replace formatDate to getDate to get date object.
Get Local Timezone Moment Js
This tutorial covers following things:
– Creating timezone list using Select element
– Set browser timezone as default value of timezone list
– Using datetime-local HTML5 input and set current datetime as default.
– Displaying date based on UTC, Local and user selected timezone.
– How to use Moment-Timezone library.