Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert UTC/ GMT datetime to CST in Javascript? (not local, CST always)

I have a challenge where backend data is always stored in UTC time. Our front-end data is always presented in CST. I don't have access to this 'black box.'

I would like to mirror this in our data warehouse. Which is based in Europe (CET). So "local" conversion will not work.

I'm wondering the simplest, most straightforward way to accurately convert UTC time (I can have it in epoch milliseconds or a date format '2015-01-01 00:00:00') to Central Standard Time. (which is 5 or 6 hours behind based on Daylight Savings).

I see a lot of threads about converting to 'local' time ... again I don't want this, nor do I simply want to subtract 6 hours which will be wrong half the year.

Anyone have any ideas? This seems to be a very common problem but I've been searching for a while, and have found nothing.

like image 282
user45867 Avatar asked Dec 18 '15 18:12

user45867


2 Answers

Using moment.js with the moment-timezone add-on makes this task simple.

// construct a moment object with UTC-based input
var m = moment.utc('2015-01-01 00:00:00');

// convert using the TZDB identifier for US Central time
m.tz('America/Chicago');

// format output however you desire
var s = m.format("YYYY-MM-DD HH:mm:ss");

Additionally, since you are referring to the entire North American Central time zone, you should say either "Central Time", or "CT". The abbreviation "CST" as applied to North America explicitly means UTC-6, while the "CDT" abbreviation would be used for UTC-5 during daylight saving time.

Do be careful with abbreviations though. "CST" might mean "China Standard Time". (It actually has five different interpretations).

like image 186
Matt Johnson-Pint Avatar answered Oct 20 '22 08:10

Matt Johnson-Pint


You can use the time zone offset to determine whether 5 or 6 hours should be subtracted.

var dateJan;
var dateJul;
var timezoneOffset;

var divUTC;
var divCST;

// Set initial date value
dateValue = new Date('10/31/2015 7:29:54 PM');

divUTC = document.getElementById('UTC_Time');
divCST = document.getElementById('CST_Time');
divUTC.innerHTML = 'from UTC = ' + dateValue.toString();

// Get dates for January and July
dateJan = new Date(dateValue.getFullYear(), 0, 1);
dateJul = new Date(dateValue.getFullYear(), 6, 1);

// Get timezone offset
timezoneOffset = Math.max(dateJan.getTimezoneOffset(), dateJul.getTimezoneOffset());

// Check if daylight savings
if (dateValue.getTimezoneOffset() < timezoneOffset) {
  // Adjust date by 5 hours
  dateValue = new Date(dateValue.getTime() - ((1 * 60 * 60 * 1000) * 5));
}
else {
  // Adjust date by 6 hours
  dateValue = new Date(dateValue.getTime() - ((1 * 60 * 60 * 1000) * 6));
}

divCST.innerHTML = 'to CST = ' + dateValue.toString();
<div id="UTC_Time"></div>
<br/>
<div id="CST_Time"></div>
like image 42
WhiteHat Avatar answered Oct 20 '22 09:10

WhiteHat