changing UTC date to local time using javascript library known as moment.js

After receiving JSON data from an ASP.NET WebAPI2 service, I noticed that the dates are stored in UTC format. However, when displayed on screen using moment.js, the time is incorrect as it assumes the date is local time.

{
    creationDate: "2014-11-18T15:16:56.363"
    ... //other fields...
}

When I try to parse the date with a specific time zone like 'Africa/Johannesburg', the time values end up being two hours behind instead of the current time. How can I properly parse and pass the date so that moment.js recognizes it as GMT+2 or SAST?

Simply adding 'UTC' to the date string doesn't seem to help, as shown in the example below:

Date.parse('2017-04-15T09:09:48.9590011 UTC')

This results in NaN, indicating that the parsing was not successful.

Answer №1

There are a couple of ways to handle this situation:

  1. Tack on a Z at the end of the string:

    moment(creationDate + "Z")
    
  2. Alternatively, you can use .utc followed by .local:

    moment.utc(creationDate).local()
    

For example, let's consider a scenario where the date provided is typically during daylight saving time, ensuring it works well for individuals in the UK (who may otherwise be confused between UTC and local time results :-) ):

var creationDate = "2014-05-18T15:16:56.363";
console.log("Original String:", creationDate);
console.log("Option 1:", moment(creationDate + "Z").toString());
console.log("Option 2:", moment.utc(creationDate).local().toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Answer №2

One common issue arises when both the client and server attempt to convert dates to their respective time zones during data exchange. The solution lies in transmitting the date as a string, thereby avoiding unnecessary conversions.

{
    creationDate: "2014-11-18 15:16:56.363"
    ... //other fields...
}

Alternatively,

data.creationDate.replace('T', ' ')

By eliminating the 'T' separator before sending or receiving data, the original date format remains intact on the client side. As a result, parsing the date with

new Date(moment(data.creationDate.replace('T', ' ')))
will yield the exact value from the server.

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

Preventing scrolling within a jQuery tab using jQuery

Looking to enhance my jqueryUI tabs by incorporating a smooth scroll bar within each tab. I've experimented with various scrollable plugins such as jQuery custom content scroller, TinyScrollbar, and now areaaperta NiceScroll. However, I continue to en ...

Tips on implementing a function within a navigation bar from a specific context

While working with a user authenticated context, I encountered an issue with the logout function. My goal is to have a link in the navigation bar that triggers the logout function and redirects me to the home page. However, I'm receiving a Typerror: l ...

The watch function in the scope is not triggered after initialization (ui-router)

Upon visiting a page, I encounter the following code: <div ng-if='$stateParams.show=="previous"'> From <input type="text" ng-model="year_from" /> <br/> To <input type="text" ng-model=" ...

Making jQuery work: Utilizing tag replacements

My current code is: this.html(this.html().replace(/<\/?([i-z]+)[^>]*>/gi, function(match, tag) { return (tag === 'p') ? match : '<p>'; return (tag === '/p') ? match : '</p& ...

How can I use JavaScript to modify the style of the first unordered list (ul) element without affecting the

function displayMenu(){ var parentElement = document.getElementById("menuItem1"); var lis = parentElement.getElementsByTagName("ul"); for (var i = 0; i < lis.length; i++) { lis[i].setAttribute("style","display: block"); } } When the button is clicke ...

Using logical equality operators in Javascript

Imagine I have two boolean variables and I need to determine when they are both true or false, essentially requiring a logical equality operator.' Most JavaScript resources recommend using bitwise operators, with the XOR operator performing a similar ...

Exploring Angularjs: Retrieving the value of a selected optgroup

When using my application, I need to extract the selected optgroup value from a dropdown menu. Here is the sample code: HTML: <select ng-model='theModel' ng-change="display(theModel)" > <optgroup ng-repeat='group in collectio ...

Transmitting data via HTML anchor tags

Is it possible to send POST data using an HTML tag? I'm aware that scripting is usually required, but I've been attempting to achieve this without success. <a class="test" onClick="assign()"><img src='<?php echo $accounts[$i][&a ...

Tips for enabling custom tags in the tinyMce editor

<textarea><div style="margin-top: 15px;"> <div class="dropdown "> <p> hello my name is <Enter Your Name> </p> <p> hehe</p> </div> </div> ...

Getting the value of a CSS variable under <script> in Vue.js

I am working on implementing a Doughnut chart using chartJs in my application. However, I want to set the color of the chart within the <script> tag and retrieve the color from theme/variables.css. In the current code snippet below, there is a hardc ...

Accessing the current route in a Vuex module using Vue.js

I've created a vuex store with namespaces that retrieves a specific store entry based on the current route parameter. import Router from '../../router/index' const options = { routeIdentifier: 'stepId' } export function fetchFr ...

When dealing with async actions in NUXT, Vuex properties may fail to reflect changes in the DOM

Just recently, I put together a small test page and store to showcase something. Based on the code, it was expected to display count = 1 initially, and then after 500ms, it should update to count = 2 as the store gets updated. Have a look at my test.vue: ...

Error Encountered: Invalid Parameter Type when Retrieving Item from AWS Dynamo

I've been facing issues when trying to establish a connection between my ReactJS application and AWS DynamoDB. Despite confirming the correctness of the API key, secret key, and region, I keep encountering an InvalidParameterType error. I have even at ...

What is the best way to filter two tables using only one search bar?

In my Vue2 application, I have implemented a pair of data tables on one of the pages. Each table is placed behind a tab, allowing users to choose which one they want to view. The search bar, however, is not confined within a tab as I wanted to avoid duplic ...

Tips for dividing an array based on a defined regex pattern in JavaScript

I want to split a string of text into an array of sentences while preserving the punctuation marks. var text = 'This is the first sentence. This is another sentence! This is a question?' var splitText = text.split(/\b(?<=[.!?])/); split ...

Is it possible for me to transform this data into JSON format and submit it using a form POST instead of using ajax

On the final step of my 7-step form, all the data input by the user on previous pages is displayed. Using jQuery, this information is dynamically added to each <td class="table_info_ans">. https://i.sstatic.net/NcuZX.png I need to convert this data ...

Developing in Java Script with ENVDTE involves adding a new project to an existing solution and placing it in a designated sub-folder for organization purposes

Currently, I am working on developing a Visual Studio extension for a new C++ project template using Visual Studio 2010. The approach I am taking involves utilizing the .vsz template method and customizing the default.js code to suit my requirements. Withi ...

Creating a Vue.js data object with items arranged in descending order

While working with vue.js, I encountered an issue in sorting the items stored in my data object. Currently, they are sorted in ascending order and I need to display them in descending order instead. Below is a snippet of my vue template: <div class="fo ...

The image we downloaded seems to indicate that our system does not support this particular file format

I have a static HTML file that is hosted on Netlify. Here is the URL: After successfully downloading the images, when I try to open them I receive an error message stating "it appears that we don't support this file format". I am unsure why this is ...

What is the best way to retrieve the current complete URL in a Next.js/Typescript component?

I'm working on a component and I need to retrieve the current full URL. Here's a simplified version of what I have: /** * Share dropdown component */ export const ShareDropdown: React.FC<{ className: string }> = ({ className, }) => { ...