In my user interface, I am attempting to display a date in a specific timezone. For this demonstration, I will be using Americas/New_York as the timezone. Here is my approach:
$scope.getStartTime = function(){
var date = new Date();
return moment(date).tz("Americas/New_York").format('YYYY-MM-DD HH:mm:ss');
};
However, when sending this data to my server, I want it to always be serialized into UTC time instead of remaining in the New York Timezone (EST).
For instance, if the time reads 12:00 P.M. in New York, I want it to be serialized as 4:00 P.M. in UTC time before being sent to the backend. This is what I attempted:
var date = getStartTime();
....
// Display the date in the UI
....
$scope.revertStartTime(date);
$scope.revertStartTime = function(startTime) {
console.log("Start time: ", startTime);
console.log("Moment: ", moment(startTime).format());
console.log("Converted to utc time: ", moment().utc(startTime).format());
return moment.utc(startTime).format("YYYY-MM-DD'T'HH:mm:ss.SSSZ");
}
I tried reverting the start time using the moment().utc()
function, hoping that it would change the date to a UTC-based one. However, it kept converting the date to the localized time instead of UTC time and I'm uncertain about the reason behind this. Any assistance would be greatly appreciated. Thank you!
Edit:
I attempted to implement the method below and here's what I did:
$scope.getStartTime = function(){
var date = new Date();
var startTime = new moment(date).tz($rootScope.userinfo.timeZone).format('YYYY-MM-DD HH:mm:ss');
$rootScope.offset = moment().utcOffset(startTime);
console.log("offset: ", $rootScope.offset);
return startTime;
};
$scope.revertStartTime = function(startTime) {
console.log("User Selected Time: ", moment().utcOffset(startTime).format('YYYY-MM-DD HH:mm:ss'));
return moment().utcOffset(startTime).format('YYYY-MM-DD HH:mm:ss');
}
Yet, all I receive is an error indicating that revertStartTime
returns an Invalid Date
.