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!
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With