What is the best way to transform a UTC/GMT date and time into CST in Javascript? (CST specifically, not based on

Dealing with a tricky situation where backend data is always stored in UTC time while our front-end data is in CST. Unfortunately, I don't have access to the system handling this 'black box' conversion.

Trying to replicate this setup in our data warehouse based in Europe (CET), so traditional "local" conversion won't suffice.

Seeking advice on the most direct and foolproof method to accurately convert UTC time (available in either epoch milliseconds or '2015-01-01 00:00:00' date format) to Central Standard Time (which could be either 5 or 6 hours behind depending on Daylight Savings).

Avoiding the common solutions of converting to 'local' time or simply subtracting 6 hours, as they are not reliable throughout the year.

If anyone has innovative suggestions for addressing this widely encountered issue, please share as my research has yielded no satisfactory answers thus far.

Answer №1

When utilizing moment.js along with the moment-timezone extension, completing this task becomes straightforward.

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

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

// customize output format as needed
var s = m.format("YYYY-MM-DD HH:mm:ss");

Furthermore, when referring to the entire North American Central time zone, it is advisable to use either "Central Time" or "CT". The abbreviation "CST" specifically denotes UTC-6 in North America, while "CDT" is used for UTC-5 during daylight saving time.

Exercise caution with abbreviations as well. "CST" may also refer to "China Standard Time" and has five different interpretations.

Answer №2

To determine whether to subtract 5 or 6 hours, you can use the time zone offset.

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>

Answer №3

Perhaps you could consider implementing a similar approach as shown below. Please keep in mind that this is just a sample and may require customization based on your specific requirements.

    const localTime = new Date(createdAt).toLocaleString("es-MX", {
    timeZone: "America/Mexico_City" });

Answer №4

To perform the conversion, you can utilize the following code snippet.

function convertUTCToPST() {
    var timeDifference = 8; // Pacific Time Zone
    var utc = new Date();
    var pst = new Date(utc.getTime()-((1 * 60 * 60 * 1000) * timeDifference));
    console.log("PST: "+pst);
}

Answer №5

const currentDate = moment(new Date()).utc().format("YYYY-MM-DD HH:mm:ss").toString()
let momentObj = moment.utc(currentDate);
momentObj.tz('America/Chicago');
const cstTime = momentObj.format("YYYY-MM-DD HH:mm:ss");

Answer №6

Feel free to utilize the code snippet provided below:

// Obtain timezone offset for Central Daylight Time or Central Standard Time
const getCdtCstOffset = () => {
  const getNthSunday = (date, nth) => {
      date.setDate((7*(nth-1))+(8-date.getDay()));
      return date;
  }
  const isCdtTimezoneOffset = (today) => {
    console.log('Today : ', today);
    let dt = new Date();
    var mar = new Date(dt.getFullYear(), 2, 1);
    mar = getNthSunday(mar, 2);
    console.log('CDT Start : ', mar);
    var nov = new Date(dt.getFullYear(), 10, 1, 23, 59, 59);
    nov = getNthSunday(nov, 1);
    console.log('CDT End : ', nov);
    return mar.getTime()< today.getTime() && nov.getTime()> today.getTime();
  }
  var today = new Date(); // current date
  if (isCdtTimezoneOffset(today)) {
    return -5;
  } else {
    return -6;
  }
}
let cstOrCdt = new Date();
cstOrCdt.setHours(cstOrCdt.getHours()+getCdtCstOffset());
console.log('CstOrCdt : ', cstOrCdt);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Pass Values in handleChange Event in Typescript

I have noticed that most online examples of handling change events only pass in the event parameter, making the value accessible automatically. However, I encountered an error stating that the value is not found when trying to use it in my handleChange fun ...

When using HTML5's checkValidity method, it may return a valid result even if

Consider the following scenario: <input pattern="[a-z]"/> If you run the command below without entering any input: document.querySelector('input').checkValidity() You will notice that it actually returns true. This seems counterintuiti ...

Overwriting Resolved Data in Angular UI-Router Child States

I'm facing an issue where the resolve function is the same in both parent and child states, but I need it to return different values based on the child state. Instead of customizing the implementation for each state, it seems to be inheriting the beha ...

"AngularJS makes it easy for the logged-in user's information to be accessible and available across

I need to ensure that user information is accessible across all views after logging in. How can I adjust the code to be able to retrieve the pseudonym from another view? Could you provide an example as well? Below is my login controller: app.controller ...

Clicking the delete button in Firebase to remove an item

I am in the process of developing a simple CRUD application and have opted for Firebase as my backend solution. While I have successfully implemented the create and read functionalities, I've hit a roadblock with the delete operation. When attempti ...

What to do while waiting for MySQL query in an asynchronous function?

Having an issue with my asynchronous function that queries the database using the mysql library. It seems like the function is not waiting for the query to complete before moving on. Here's the code snippet: async (eventName, eventArgs, app) => { ...

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

The conversion of Draft-js JSON to EditorState is not functioning correctly

Recently, I utilized Draft-js to generate blog posts. When a user creates a post, the data is transformed into a string and dispatched to the server for storage. The conversion of draft-js EditorState looked like this: JSON.stringify(convertToRaw(editorSta ...

Switch the view to a grid layout upon clicking

Using bootstrap 5, I've successfully created a list view: <div class="col"> Click to switch to grid/list </div> Below is the content list: <div class="row mt-3 list"> list view ... ..... ....... </div ...

What is the process for exporting a plugin from dayjs() in JavaScript?

Currently, I have incorporated the plugin isToday() to enhance the capabilities of dayjs(). Nevertheless, I am uncertain about how to export isToday() in order to utilize it across other files. import isToday from "dayjs/plugin/isToday"; expor ...

Resource loading unsuccessful: server encountered a status of 500 (Internal Server Error)

I'm struggling to figure out why I keep getting an Internal Server Error when trying to call a web service in my HTML page using JavaScript and Ajax. Here is the error message: Failed to load resource: the server responded with a status of 500 (Int ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

Tips for receiving notifications when the Collapsible collapses

I'm having trouble figuring out how to receive notifications when the Collapsible is expanded and collapsed. Currently, I am not receiving any type of notification. Any suggestions on how to make this work? Below is my code: --Imported jQuery < ...

Error: Unable to register both views with identical name RNDateTimePicker due to Invariant Violation

Encountering an issue while attempting to import: import DropDownPicker from 'react-native-dropdown-picker'; import DateTimePicker from '@react-native-community/datetimepicker'; <DropDownPicker zIndex={5000} ...

The information from the form is not appearing in the req.body

Utilizing the mean.js framework, I have the bodyParser middleware configured as shown below: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); Additionally, I am using formidable to upload imag ...

Using a loop to iterate through a multidimensional array in Node.js or JavaScript, creating additional data and adding new key-value pairs

Here is an array of objects showcasing different intents and results : var finalresult = [{ "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)", "data": [{ "intent": "delivery", "result": [{ "h ...

Is the for loop programmed to stop at the first match?

I've been working on filtering a txt file using nodejs. Here's my code snippet: const fs = require('fs') let list = fs.readFileSync('./newmR.txt', 'utf-8').split('\r\n') console.log(list.length) ...

Experiencing a blank array when using filtering/search text in a Nodejs application with MongoDB

I am experimenting with search functionality in a MongoDB database using Node.js. However, my result array is always empty. I have shared my code here and would appreciate some assistance in identifying the issue. Whenever I perform a search, I end up with ...

Determining the specific condition that failed in a series of condition checks within a TypeScript script

I am currently trying to determine which specific condition has failed in a set of multiple conditions. If one does fail, I want to identify it. What would be the best solution for achieving this? Here is the code snippet that I am using: const multiCondi ...

Implementing JavaScript Functions to Trigger Control Key and Plus/Minus Events

In my project, I have a unique set of selectors called A+. By clicking on the A+ button, it has been programmed to initiate the control plus event. Similarly, within the same interface, I also have an A- button that activates the control minus event when ...