May 13, 2018

JavaScript: Select Date Time with Timezone

This tutorial explains how to implement to get a JavaScript date object from user selected date time & timezone and the date object can be sent server side to save or for further processing. HTML5 provides input type 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.

HTML

Here is the HTML code for user input of datetime and timezone:


<div class="container">
					<input type="datetime-local" id="pickerDateTime" />	
					<select id="dropdownTimeZone"></select>
					<input type="button" id="btnSubmit" onclick="submitDate()" value="Calculate" />
				</div>

To get different datetime results, the following code is used:


<div class="report">
					<label>Browser/Local datetime</label>
					<div id="divLocal">
					</div>    

					<label>UTC of browser datetime</label>
					<div id="divUTC"></div>

					<label>Selected datetime with timezone</label>
					<div id="divSelected">
					</div>  

					<label>UTC of selected datetime with timezone</label>
					<div id="divUTCSelected">
					</div>  
				</div>

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.


<script src="moment.min.js"></script>
<script src="moment-timezone-with-data.min.js"></script>

You can use CDN version:


<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.3/moment-timezone-with-data.min.js"></script>

Add a script tag before </body> and add following code to get timezone names:


 function loadTimeZoneList(){   
     let select = document.getElementById("dropdownTimeZone");
	 select.innerHTML = ""; 
	 let browserTimeZone = moment.tz.guess();
	 let timeZones = moment.tz.names();
		timeZones.forEach((timeZone) =>{
		option = document.createElement("option");		
		  option.textContent = `${timeZone} (GMT${moment.tz(timeZone).format('Z')})`; 
		  option.value = timeZone;
		  if (timeZone == browserTimeZone){
			  option.selected = true;
		  }
		  select.appendChild(option);
		});
	
   }

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:


function loadDefaultDateTime(){
		document.getElementById('pickerDateTime').value = moment().format('YYYY-MM-DDTHH:mm');
	}

Date Formats

Let's create a common format to see different dates:


const DEFAULT_FORMAT = 'YYYY-MM-DD HH:mm:ss Z';	

 function formatDate(momentDate){
		return momentDate.format(DEFAULT_FORMAT);
   }

We will use it before displaying the date.

Here are the methods to get UTC, user selected datetime with timezone and its UTC value:

   
   function getUtcValue(localDateTime){
		return moment(localDateTime).utc();
   }

   function getSelectedValue(localDateTime, timeZone)
   {
		return moment.tz(localDateTime,timeZone);
   }

   function getSelectedUTCValue(localDateTime, timeZone)
   {
		return moment.tz(localDateTime,timeZone).utc();
   }

Let's implement submitDate method which is called on Calculate button click:



   function submitDate(){

	let localValue = document.getElementById('pickerDateTime').value;
	let timeZoneValue = document.getElementById("dropdownTimeZone").value;

	let local =  document.getElementById('divLocal');
	local.innerHTML = formatDate(moment(localValue));

	let utc =  document.getElementById('divUTC');
	utc.innerHTML = formatDate(getUtcValue(localValue));

	let selected =  document.getElementById('divSelected');
	selected.innerHTML = formatDate(getSelectedValue(localValue,timeZoneValue));

	let utcSelected =  document.getElementById('divUTCSelected');
	utcSelected.innerHTML = formatDate(getSelectedUTCValue(localValue,timeZoneValue));
   }

As we are loading current date time and browser timezone by default, let's call submitDate to get results by default.


function init(){
		loadDefaultDateTime();
		loadTimeZoneList();  
		submitDate();
	}

	init();

Output

When you run the page, you will get following datetimes

Javascript date time timezone

This is just sample to display the datetimes. If you want to get JavaScript date object, you can use following method:


  function getDate(momentDate){
		return momentDate.toDate();
   }

and replace formatDate to getDate to get date object.

Conclusion

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.

Enjoy JavaScript!!