Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Local to UTC and UTC to Local in angular5?

I have a DateTimePicker on my page, where the user selects the datetime in their local timezone. But when we save that in the DB, I need to convert this to UTC and save it. Similarly, while displaying this to the user, again I need to convert from UTC to user's local timezone.

Saving: LOCAL timezone to UTC
Displaying: UTC to LOCAL timezone

As the server might reside on other locations, I thought it would be correct to convert the value to UTC at the client itself. Not sure, if there is a better way of doing this. So, was trying for the same in my angular5 page.

Not so familiar with moment.js, and so couldn't completely understand on how it actually works. Any tips to do this in a better way in angular?

Below is how I achieved..

convertUtcToLocalString(val : Date) : string {        
    var d = new Date(val); // val is in UTC
    var localOffset = d.getTimezoneOffset() * 60000;
    var localTime = d.getTime() - localOffset;

    d.setTime(localTime);
    return this.formatDate(d);
}

convertUtcToLocalDate(val : Date) : Date {        
    var d = new Date(val); // val is in UTC
    var localOffset = d.getTimezoneOffset() * 60000;
    var localTime = d.getTime() - localOffset;

    d.setTime(localTime);
    return d;
}

convertLocalToUtc(val : Date) : Date { 
    var d = new Date(val);
    var localOffset = d.getTimezoneOffset() * 60000;
    var utcTime = d.getTime() + localOffset;

    d.setTime(utcTime);
    return d;
}

Appreciate your help.

Thanks!

like image 776
Neelima Ediga Avatar asked Jan 29 '23 14:01

Neelima Ediga


1 Answers

You could use the moment module in angular.

import * as moment from "moment";

From local to UTC:

moment(local_date).toDate();

From UTC to local:

moment.utc(utc_date).toDate()
like image 140
Manoj De Mel Avatar answered Jan 31 '23 23:01

Manoj De Mel