Handling Issues of Conversion in GMT and UTC in Javascript
Posted By : Ranjan Mondal | 26-Sep-2018
Introduction:
UTC and GMT are often confused and interchanged as well.
But GMT is time zone and UTC is time standard.
for example, India has its own GMT which +5.30 ahead of UTC.
Full form of UTC is Coordinated Universal Time.
Full form of GMT is Greenwich Mean Time.
Problems come across the development is when we date in long format from our browser to the backend which usually runs in java or node technologies.
And browsers run on javascript. The date goes in GMT format and backend save the date in UTC format. Both dates are same but their digits are varied substantially.
for example, if we send data as 1st Oct 2018 5:30 am, the server will save it as 1st Oct 2018 0.00 am.
To avoid any the discrepancy. We can use the following code to convert the time in UTC format and let the date as it is.
/**
* get date in GMT but time in UTC format
* for passing data to backend server which usually on UTC timezone
* @param localDate
*/
getUtcDate(localDate) {
let date = new Date(localDate);
let currentDate = new Date();
let now_utc = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(),
currentDate.getUTCHours(), currentDate.getUTCMinutes(), currentDate.getUTCSeconds());
return now_utc;
}
And when the date comes from a server in long format, They usually get converted in GMT format in the browser.
So you can following code to convert a date in UTC format (String) and display in the browser as it is.
/**
* get UTC formated date from GMT date in a string format
* No need to use pipe filter to show on html
* @param date
*/
getFormatedDateInUTC(date) {
if (!date) {
return "N.A";
}
let currentdate = new Date(date);
let month = (currentdate.getUTCMonth() + 1) < 10 ? '0' + (currentdate.getUTCMonth() + 1) : (currentdate.getUTCMonth() + 1);
let day = currentdate.getUTCDate() < 10 ? '0' + currentdate.getUTCDate() : currentdate.getUTCMonth();
let hours = currentdate.getUTCHours() < 10 ? '0' + currentdate.getUTCHours() : currentdate.getUTCHours();
let mins = currentdate.getUTCMinutes() < 10 ? '0' + currentdate.getUTCMinutes() : currentdate.getUTCMinutes();
let secs = currentdate.getUTCSeconds() < 10 ? '0' + currentdate.getUTCSeconds() : currentdate.getUTCSeconds();
return ("" + currentdate.getUTCFullYear() + "-" + month + "-" + day + " " + hours + ":" + mins + ":" + secs);
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ranjan Mondal
Ranjan is a bright Web App Developer, and has good knowledge of Core java, Spring and hibernate.