Search code examples
momentjsmoment-timezone

Code to parse a local date, time, and timezone into a UTC string with Moment.js


In separate fields, I collect DisplayDate, DisplayTime, and TimeZone from the user. I want to put those into a moment and output the UTC formatted string to save into a hidden field that gets sent back to the server. I used the below code, but it uses the local timezone, rather than the selected TimeZone I entered. How do I get it to observe selTimeZonesVal?

var startTime = $('#StartTime');
var displayDateVal = $('#DisplayDate').val();
var displayTimeVal = $('#DisplayTime').val();
var selTimeZonesVal = $('#TimeZones').val();

var dtMoment = moment(displayDateVal + ' ' + displayTimeVal).tz(selTimeZonesVal);
var formattedUtc = dtMoment.utc().format('YYYY-MM-DDTHH:mm:ss');
startTime.val(formattedUtc);

Solution

  • The problem was with the date parsing. Somehow, moment was able to parse the date, but it would ignore the timezone if the date wasn't in ISO format.

    The fix:

    var startTime = $('#StartTimeUtc');
    var displayDateVal = $('#DisplayDate').val();
    var displayTimeVal = $('#DisplayTime').val();
    var selTimeZonesVal = $('#TimeZones').val();
    
    // Massage the date so moment can parse it (moment doesn't like mm/dd/yyyy)
    var localDT = new Date(displayDateVal + ' ' + displayTimeVal);
    var parseDT = moment(localDT).format('YYYY-MM-DDTHH:mm:ss')
    
    var dtMoment = moment.tz(parseDT, selTimeZonesVal);
    var formattedUtc = dtMoment.utc().format('YYYY-MM-DDTHH:mm:ss');
    startTime.val(formattedUtc);