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

I have a problem when the underlying data is always stored in UTC. Our foreground data is always presented in CST. I do not have access to this black box.

I would like to reflect this in our data warehouse. Which is based in Europe (CET). Therefore, the "local" conversion will not work.

I am interested in the simplest, easiest way to accurately convert UTC time (I can get it in milliseconds of an era or the date format "2015-01-01 00:00:00") to Central Standard Time. (which is 5 or 6 hours compared to summer savings).

I see a lot of threads about converting to "local" time ... again I do not want this, and I just do not want to subtract 6 hours, which will be incorrect for six months.

Does anyone have any idea? This seems like a very common problem, but I searched for a while and found nothing.

+4
source share
2 answers

Using moment.js with a moment-time addition 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");

, , " ", "CT". "" UTC-6, "CDT" UTC-5 .

. "" " ". ( ).

+5

, , 5 6 .

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>
Hide result
0

Source: https://habr.com/ru/post/1620805/


All Articles