momentjsangular-moment

How can I Convert Eastern Standard Date Time to Utc using moment js?


How can I Convert Eastern Standard Date Time to Utc using moment js while my browser time will remain the Pakistan Standard Time


Solution

  • You can use the tz() function to create a date in Eastern Standard Time.

    You can then use .utc() to convert this to UTC.

    If you want another timezone (say Pakistan) you can use .tz() again to convert:

    // Our input time (in Eastern Standard Time).
    const inputTime = '2021-09-03 04:45:00';
    
    // Create our moment object in Eastern Standard Time
    const easternTime = moment.tz(inputTime, 'EST');
    console.log('Times:')
    console.log('Eastern: ', easternTime.format());
    
    // Now use .utc() to convert to utc timezone.
    const utcTime = easternTime.utc();
    console.log('UTC:     ', utcTime.format());
    
    // Now use .tz() to convert to Pakistan Standard Time.
    const pakistanTime = utcTime.tz('Asia/Karachi');
    console.log('Pakistan:', pakistanTime.format());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>