Transforming the time from the local timezone to Coordinated Universal Time (

I need help figuring out how to convert a Javascript date object to UTC, assuming a timezone like America/New_York:

2019-01-04T00:00:00.000Z

The desired result is to convert this to a date object in UTC.

2019-01-04T05:00:00.000Z

const timezone = 'America/New_York';
const localMidnight = new Date(Date.UTC(2019, 0, 4)) // 2019-01-04T00:00:00.000Z
moment.tz(localMidnight, timezone).utc().toDate()

Despite the efforts, the function is still returning the same value as the input date 2019-01-04T00:00:00.000Z.

> m(localMidnight, 'America/New_York').tz('utc').toDate()
2019-01-04T00:00:00.000Z
> m(localMidnight, 'America/New_York').tz('UTC').toDate()
2019-01-04T00:00:00.000Z
> m(localMidnight, 'America/New_York').utc().toDate()
2019-01-04T00:00:00.000Z

Answer №1

It appears that the issue stemmed from the date format you used. In this instance, you can observe that the .toISOString() function appends a Z at the end. In order for the moment.tz method to function properly, you must exclude that character from the format.

For instance, consider the following scenario where a new date is generated in 'America/New_York' and the time zone is changed to UTC:

const timezone = 'America/New_York';
const localMidnight = new Date(2019, 01, 04);

console.log("Original time:")
console.log(localMidnight.toISOString());

console.log("Converted to UTC:");
console.log(moment.tz(localMidnight.toISOString().slice(0, -1), timezone).utc().format());   
<script type="text/javascript" src="http://momentjs.com/downloads/moment.min.js"></script>
<script type="text/javascript" src="http://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>

Answer №2

If you're looking to generate a date using a specific timezone and then convert it to an ISO 8601 timestamp in UTC, the code snippet below should help you achieve that.

Feel free to refer to the comments within the code for explanations, and don't hesitate to reach out if you require further assistance.

// Generate a moment object for midnight in America/New_York
var newYork = moment.tz("2019-01-04 00:00", "America/New_York");

// Create an ISO 8601 timestamp in UTC
console.log(newYork.utc().format()); // 2019-01-04T05:00:00Z
<script type="text/javascript" src="http://momentjs.com/downloads/moment.min.js"></script>
<script type="text/javascript" src="http://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>

Keep in mind that using the utc function will switch to UTC mode, which may have additional effects apart from converting to ISO 8601 format.

Answer №3

To achieve the desired outcome, follow the instructions below:

Syntax - moment(date).tz(timezone).utc().format()

For the format YYYY-MM-DDTHH:mm:ss.SSSZ, use toISOString() instead of format()

const timezone = 'America/New_York';
const localMidnight = new Date(Date.UTC(2019, 0, 4))
console.log("newTime in utc",  moment(localMidnight).tz(timezone).utc().format())
console.log("newTime",  moment(localMidnight).tz(timezone).utc().toISOString())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.js"></script>

codepen - https://codepen.io/nagasai/pen/gZegqd?editors=1010

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

Ways to prevent websites from switching to landscape mode

Is there a way to prevent landscape mode on my website and restrict users to portrait mode, especially for devices with screen widths below 777px? I have custom headers that take up fixed position space of around 100px on the screen. If it is possible to ...

Steer clear of chaining multiple subscriptions in RXJS to improve code

I have some code that I am trying to optimize: someService.subscribeToChanges().subscribe(value => { const newValue = someArray.find(val => val.id === value.id) if (newValue) { if (value.status === 'someStatus') { ...

Set up your Typescript project to transpile code from ES6 to ES5 by utilizing Bable

Embarking on a new project, I am eager to implement the Async and Await capabilities recently introduced for TypeScript. Unfortunately, these features are currently only compatible with ES6. Is there a way to configure Visual Studio (2015 Update 1) to co ...

CKEditor Image Upload Troubles

I'm encountering difficulties with image uploads while using CKEditor for the first time. Despite multiple attempts, I can't seem to get the image upload feature to work. My approach to resolving this issue involves utilizing JavaScript and PHP ...

Creating a dynamic website with user-friendly editing capabilities

Having a good understanding of html5 and css3, I am currently exploring ways to create a website that enables visitors to edit content in real time for all other users to see. While aware of the contenteditable attribute, I have found that it does not reta ...

Exploring the vueJS canvas life cycle and transitioning between components

Struggling with displaying Vue components that contain a canvas with different behaviors. Looking to switch components using v-if and passing different properties. Here's a small example: Currently, when switching from 'blue' to 'red ...

Are there alternative methods, aside from using a computed property, that can be utilized to store a Vue route parameter in a way where

In my Vue component, I am working on passing a route parameter through XHR requests and potentially using it in other areas as well. Initially, I considered storing it as a data attribute but realized that it could be modified by someone. Then it occurred ...

Ways to eliminate brackets from a string

Currently, I am working on a challenge involving replacing strings using a function that accepts a string and an object of values. This task involves a two-part algorithm: Replacing values within the string that are enclosed in braces. If the value is wi ...

Stop users from typing inside a newly inserted element in contenteditable mode

Currently, I am developing a straightforward syntax highlighter that transforms text into DOM elements with specified classes. For example, consider the following: <div contenteditable="true"> Some text. | And some other text. </div> Assum ...

Encountering a problem with AngularJS ui router templates

I have defined the following routes in my project: $stateProvider .state('access', { abstract: true, url: '/access', templateUrl: 'login.html' }) .state('access.signin', { ...

Switching a component in Mui App transforms the entire aesthetic

I'm currently working on a project using Mui and the Material Kit theme. While I initially tried to customize the default components provided by Material Kit using custom CSS, I found that I was unable to override the styles as expected. Consequently, ...

What could be preventing my CSV file from being saved empty?

I am currently working on a function that processes the results of a web scraping operation I conducted on an online t-shirt store. Every t-shirt is represented as an object, featuring attributes such as title, price, imgUrl, URL, and time. These objects ...

The issue with the ng-click property not triggering arises when it is assigned to a button that is generated dynamically

I need to construct a table dynamically based on the results returned from SQL. In this scenario, populating the table with the start time, end time, and user is straightforward: var StartTime = document.createElement('td'); var EndTime = docume ...

I am unable to pass the req.params.id value as an input to a function located in a separate file

In my project, I've developed a REST API for user and coupon management. The main file driving this API is called coupon-api.js. This file contains the route definitions, while the functions to handle these routes are separated into two distinct files ...

Allowing input fields to accept decimal numbers

I am currently facing an issue with an input field that is set to type=number, which does not allow for decimal numbers. However, I need to enable users to input decimal numbers but haven't been able to make it work. Would using regex be a possible so ...

The PHP function is failing to communicate with jQuery and Ajax

Having trouble with PHP return to jQuery/Ajax functionality, When I try to edit an item, the error message displays even though the success function is executed. On the other hand, when attempting to delete an item, nothing is displayed despite the succes ...

React Error boundary is failing to perform as anticipated

Having issues implementing an error boundary in React. Here is the code snippet: ErrorBoundary.js import React from 'react'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: fal ...

Design the parent element according to the child elements

I'm currently working on a timeline project and I am facing an issue with combining different border styles for specific event times. The main challenge is to have a solid border for most of the timeline events, except for a few instances that share a ...

Facing an issue with sending data in AJAX Post request to Django View

I have been trying to send data from the frontend to the backend of my website using AJAX. Below is the post request view in my Django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} ...

The specified type '{}' cannot be assigned to type 'ReactNode'

Can someone help me figure out why I am getting this error in Vercel but not locally? Error: 'FontAwesomeIcon' cannot be used as a JSX component. ./components/Services/ServiceContainer.tsx:25:6 12:01:54.967 Type error: 'FontAwesomeIcon&a ...