Showing the date formatted for timezone as Coordinated Universal Time

In my user interface, I am attempting to display a date in a specific timezone. For this demonstration, I will be using Americas/New_York as the timezone. Here is my approach:

    $scope.getStartTime = function(){
        var date = new Date();
        return moment(date).tz("Americas/New_York").format('YYYY-MM-DD HH:mm:ss');
    };

However, when sending this data to my server, I want it to always be serialized into UTC time instead of remaining in the New York Timezone (EST).

For instance, if the time reads 12:00 P.M. in New York, I want it to be serialized as 4:00 P.M. in UTC time before being sent to the backend. This is what I attempted:

    var date = getStartTime();
    ....
    // Display the date in the UI
    ....
    $scope.revertStartTime(date);

    $scope.revertStartTime = function(startTime) {
        console.log("Start time: ", startTime);
        console.log("Moment: ", moment(startTime).format());
        console.log("Converted to utc time: ", moment().utc(startTime).format());
        return moment.utc(startTime).format("YYYY-MM-DD'T'HH:mm:ss.SSSZ");
    }

I tried reverting the start time using the moment().utc() function, hoping that it would change the date to a UTC-based one. However, it kept converting the date to the localized time instead of UTC time and I'm uncertain about the reason behind this. Any assistance would be greatly appreciated. Thank you!

Edit:

I attempted to implement the method below and here's what I did:

    $scope.getStartTime = function(){
        var date = new Date();
        var startTime = new moment(date).tz($rootScope.userinfo.timeZone).format('YYYY-MM-DD HH:mm:ss');
        $rootScope.offset = moment().utcOffset(startTime);    
        console.log("offset: ", $rootScope.offset);
        return startTime;
    };

    $scope.revertStartTime = function(startTime) {
        console.log("User Selected Time: ", moment().utcOffset(startTime).format('YYYY-MM-DD HH:mm:ss'));
        return moment().utcOffset(startTime).format('YYYY-MM-DD HH:mm:ss');
    }

Yet, all I receive is an error indicating that revertStartTime returns an Invalid Date.

Answer №1

Here are a few key points to consider:

  • It's worth noting that the correct zone ID is America/New_York, not Americas/New_York.

  • When working with moment.js, you have options like moment.utc(foo) or moment(foo).utc() for handling UTC conversion. Avoid using moment().utc(foo) as it behaves differently. The timestamp value remains unchanged during these conversions.

  • You can use .toISOString() to get the ISO format regardless of the mode you're in. This simplifies the process without switching to UTC mode explicitly.

  • If you start with a specific point in time and end up converting to UTC, any timezone changes in between won't affect the output. For example, all the following methods yield equivalent results:

    moment().toISOString()
    moment.utc().toISOString()
    moment(new Date()).toISOString()
    moment.utc(new Date()).toISOString()
    moment(new Date()).utc().toISOString()
    moment().tz('America/New_York').toISOString()
    moment.tz('America/New_York').toISOString()
    moment().utcOffset(1234).toISOString()
    moment.utc().format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]')
    moment().utc().format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]')
    

    Only the last two expressions require being in UTC mode, as the format function varies based on the mode or timezone specified.

Answer №2

If you want to achieve this, the best approach would be to utilize the .utcOffset() method. This method is recommended starting from Moment 2.9.0. It calculates the actual offset from UTC, rather than the inverse offset (e.g., -240 for New York during DST). Offset strings like "+0400" still function the same way:

// always "2013-05-23 00:55"
moment(1369266934311).utcOffset(60).format('YYYY-MM-DD HH:mm')
moment(1369266934311).utcOffset('+0100').format('YYYY-MM-DD HH:mm')

The previous .zone() method as a setter was declared obsolete in Moment.js 2.9.0. It used to accept a string with a timezone identifier (e.g., "-0400" or "-04:00" for -4 hours) or a number indicating minutes behind UTC (e.g., 240 for New York during DST).

// always "2013-05-23 00:55"
moment(1369266934311).zone(-60).format('YYYY-MM-DD HH:mm')
moment(1369266934311).zone('+0100').format('YYYY-MM-DD HH:mm')

If you need to handle named timezones instead of numerical offsets, make sure to incorporate Moment Timezone and utilize .tz() instead:

// determines the correct offset for America/Phoenix at the given moment
// always "2013-05-22 16:55"
moment(1369266934311).tz('America/Phoenix').format('YYYY-MM-DD HH:mm')

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

One way to eliminate a prefix from a downloaded file path is by trimming the URL. For example, if you have a URL like "http://localhost

As my web app runs on port number, I am looking to download some files in a specific section. However, the download file path is being prefixed with "". <a href={file_path} download={file_name}> <Button variant={"link"}> <b>Dow ...

When accessing a site using HTTPS, jQuery.ajax fails to send the necessary ajax headers

Every time I initiate a jQuery.ajax request, it functions properly when the URL is using the HTTP protocol. However, if I send the same request to an HTTPS server, it gets sent without the header [HTTP_X_REQUESTED_WITH:XMLHttpRequest], which means that the ...

"Upon invoking the console log, an empty value is being returned when attempting to access the

Why is console.log returning a blank line when trying to retrieve the value of a text input variable? HTML <label for="subject">Subject</label> <input type="text" id=" ...

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

Executing a jQuery AJAX request to pass an array of values to a Controller action

I'm attempting to send an array of checkbox values from an Ajax form in MVC to a controller action. Below is the code I am using: The form (inside a modal): @using (Ajax.BeginForm("GetPrintableProject", "Project", null, new AjaxOptions { HttpMethod ...

The inline script is deemed non-compliant as it infringes upon the Content Security Policy directive: "script-src 'self'"

My chrome-extension is built using react-create-app. However, I encountered an error when running npm run build in react-create-app: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src &apo ...

The problem of interpreting JSON using the JavaScript eval() function

Here is the JSON string provided : { "name":"Ruby on Rails Baseball Jersey", "price":"19.99", "id":"1025786064", "image":"" }, { "name":"Ruby on Rails Baseball Jersey", "price":"19.99", "id":"1025786064", "image":"" }, { "name ...

Error: Unable to locate module: 'fs' in Next.js

import nookies from 'nookies'; import { firebaseAdmin } from "../firebaseAdmin"; import { TChildren } from "../types/app/app.types"; interface Props { children: TChildren; } export default function ProtectedRoute(props ...

What is the best way to incorporate child nodes when selecting dynamically generated elements through JavaScript?

Currently, I have buttons being dynamically generated on the page using plain JavaScript. For example: <button class="c-config__option c-config__option--button c-config__option--pack" data-index="0"> Item 1 <span>Subtext</span> ...

What are the solutions for resolving the Express.js 404 status error?

I am new to node.js and express.js and I am attempting to create a login form using MERN. Whenever I try to access the register route, I keep getting a 404 status error and I can't figure out what's wrong with my code. Can someone please help m ...

Prevent Node.js Express from automatically creating sessions

When I activate the session option in express using app.use(express.session({secret: "12345"}));, a session cookie is automatically created when the user visits a page for the first time. Is there a way to turn off this automatic behavior and have more co ...

Displaying a div on click using Jquery will only impact one div at a time

I am encountering an issue with my WordPress setup. Within my loop, I have a clickable link that toggles a div to show or hide content. However, since each item in the loop uses the same class, clicking on one link activates all of them simultaneously. &l ...

Saving solely the content of an HTML list element in a JavaScript array, excluding the image source

One issue I am facing is with an unordered list in HTML which contains items like <ul id="sortable"> <li class="ui-state-default"><img src="images/john.jpg">John</li> <li class="ui-state-default"><img src="images/lisa.jpg ...

Enhance Your Images with Fancybox 2.1.5 by Adding Titles Directly to the Photo Window

I need help figuring out how to place the title text inside the photo box on this particular page: Despite my efforts and multiple Google searches, I have not been successful in achieving this. As a newcomer to javascript, I am struggling with implementin ...

Is this AJAX request properly formatted?

I am attempting to send an array of variables to my CakePHP action for editing purposes. The array is created from the ids of table rows. Below is the javascript code snippet that can be found in my index.ctp file. <script type="text/javascript"> $( ...

Is there a way to efficiently execute an API function for every element within an array in a sequential manner?

I am currently facing a challenging problem while working with Angular and RxJs. I have an array containing several IDs: ids = [1,2,3,4] There is an API that can be called with a specific ID parameter to delete the corresponding item from the database: th ...

Enhancing the Angular UI Bootstrap Accordion: Customizing the header with a new class

I currently have a functional accordion implemented as shown below <accordion-group is-open="open.first"> <accordion-heading> My Title </accordion-heading> </accordion-group> The "Accordion-heading" direc ...

Hourly Average Totals Across Various Days of the Week

I found some guidance in this post that helped me make progress: SELECT [Day], [Hour], [DayN], AVG(Totals) AS [Avg] FROM ( SELECT w = DATEDIFF(WEEK, 0, ForDateTime), [Day] = DATENAME(WEEKDAY, ForDateTime), ...

Understanding the significance of the ~ symbol in a JavaScript function

Currently, I am going through this javascript function: if (~['bacon', 'burger'].indexOf(type)) { this.res.writeHead(200, { 'Content-Type': 'text/plain' }); this.res.end('Serving ' + type + ' ...

I am getting zero results when trying to retrieve data from the users table in Parse Server

Using Parse Cloud to update user information, the user is in the database but querying the users table returns nothing. There is a desire to update a field and save it back. Below is the cloud function being used: Parse.Cloud.define("update", async(reques ...