Receive AngularJS time data from a server in GMT and display it on your local computer's date

After receiving a response from a service, the date returned is in GMT format. However, I need to convert this date to my local time and display it as 5-22-2016. The problem arises when trying to change the time to match my local computer.

The response structure is as follows:

createdDate: "2016-04-22 16:48 PM GMT"
description: "File Upload Success"
fileGuid:"62e7250c-d5ed-41e2-b5b2-4600094d9a7c"
fileSize:"191429"

There are a total of 90 objects in my array, and I am attempting to use the _each function to iterate through all key-value pairs:

_.each(data, function(value, key) {
    console.log(key, value);
    var strDateTime = value.createdDate;
    var myDate = new Date(strDateTime);
    data[key].createdDate = (myDate.toLocaleString()).split(',')[0];
    console.log("data", data)

Despite this approach working for some created dates, there are instances where it returns an invalid result. Any suggestions on how to resolve this issue?

Answer №1

Upon reviewing the guidelines outlined in ECMA-262 5.1 15.9.1.15 Date Time String Format, it appears that some of your data may not be in the correct format.

It should be noted that ECMAScript has established a standardized string format for date-times, which is a simplified version of the ISO 8601 Extended Format. The prescribed format is: YYYY-MM-DDTHH:mm:ss.sssZ.

To address this issue, consider utilizing the versatile moment.js library.

By incorporating moment.js into your code, you can make the necessary updates as shown below:

moment('2016-5-5').toLocaleString() //'Tue May 05 2015 00:00:00 GMT+0800'

Furthermore, if your objective is solely display-related, you may want to explore an Angular directive alternative known as angular-moment.

Hopefully, these suggestions prove useful. :)


I appreciate the observation brought to my attention by @RobG, prompting me to update MDN references with ECMA-262 standards.

Regarding the input

moment("2016-04-22 16:48 PM GMT")
, you can refer to the accompanying image by clicking on the link provided below:

https://i.sstatic.net/UUUrA.jpg

Answer №2

It is recommended to manually parse date strings as it can be easily done with a custom parsing function if the format is consistent.

If your dates are always in GMT and follow the format '2016-04-22 16:48 PM GMT', you can consider using a function like the one provided below.

If you need the output string in a specific format, you can either use toISOString, which gives an ISO 8601 format with GMT time zone, or create your own formatting function to get the desired output.

var s = '2016-04-22 16:48 PM GMT';

// Function to parse a string into Date object
function parseSpecial(s) {
  var b = s.split(/[-\s:]/);
  var h = (b[3]%12) + (/pm/i.test(s)? 12: 0);
  return new Date(Date.UTC(b[0], b[1]-1, b[2], h, b[4]));
}

// Function to format a date into mm/dd/yyyy hh:ss a format
function myFormat(date) {
  function z(n){return (n<10?'0':'') + n}
  var h  = date.getHours();
  var ap = h > 11? 'pm' : 'am';
  h = h%12 || 12;
  return z(date.getMonth() + 1) + '/' + z(date.getDate()) + '/' +
         date.getFullYear() + ' ' + z(h) + ':' + z(date.getMinutes()) +
         ' ' + ap;
}

var d = parseSpecial(s);

document.write(s +   // Original string
          '<br>' + d.toISOString() +  // As ISO 9601 long format string
          '<br>' + myFormat(d)        // As local date and time
          + ' (your local date and time equivalent)');

You can opt for a library to handle all of this, but it's entirely up to you. For instance, with moment.js, you could achieve the same functionality with:

// Parse the string, specifying the format
var s = '2016-04-22 16:48 PM GMT';
var d = moment(s.replace('GMT','Z'), 'YYYY-MM-DD hh:mm a Z');

// Generate a string representing local time in the required format
console.log(d.format('DD/MM/YYYY hh:mm a'));

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

Alter the button's color seamlessly while staying on the same page

I have implemented a feature that allows me to change the category of photos without having to leave the page and it works perfectly. My next goal is to create a button system where the pre-defined category of a photo is indicated by a button with a green ...

JavaScript Date behaving oddly

While working with Javascript, I encountered a puzzling issue involving the Date object. date1 = new Date(1970, 1, 1); date2 = new Date("1970-01-01T13:00:00.000Z"); console.log(date1.getYear()); //70 console.log(date1.getMonth()); //1 console.log(date1.g ...

Delving into the intricacies of Promises/A+ and the mechanics of Asynchronicity in Javascript

I am new to JavaScript programming and may have some questions that seem basic. I was recently following a tutorial on Spring Boot and React. The author used a library called "rest" (package.json - "rest": "^1.3.1") and mentioned it is a Promises/A+ based ...

Having trouble accessing functions within the webpack bundle

As someone new to the world of JS library development, I have embarked on a journey to achieve the following goals: Creating a library with TypeScript Generating a bundle using webpack5 Publishing the library to npm Utilizing the library in other projects ...

What is the best way to submit a Redux Form only if there have been changes made to any of the fields

I'm currently using Redux Form version 7.1.2, and I have a form that submits data when the user clicks the submit button. In the function assigned to handle the submission, I perform an action. However, I only want this action to be executed if there ...

Using ngmodel in Angular to assign a value to the Angular Material datepicker

Having an issue with editing the selected value in a custom control value accessor for an Angular Material date component. The input field is returning empty. App.Component.Html <date-input ngModel="dateValue" name="dateName"> ...

I am encountering a problem while performing JavaScript validations

In jQuery or using the element's ID, I can validate a textbox. For example: var field = document.getElementById('tbxSearchField').value if (field == "") {alert("please enter text");} The HTML code is as follows: <input class="input" id ...

Navigating to the end of a kendo list view control

My current project requires that the most recent item be displayed at the bottom of the kendo listview control, with the scroll positioned accordingly. I have attempted a few methods to achieve this but have not been successful: listView.select(listView. ...

Pause the jquery script when a key is pressed

Currently, I have a script that loads a php file within a div and automatically refreshes every 5 seconds. Check out the code below: $("#load_timeout").load("time_out.php"); var refreshId = setInterval(function() { $("#load_timeout").load('time_o ...

Steps for converting a file with JSON objects to a JSON array

I have a JSON file with multiple objects stored in a single file that I need to convert into a JSON array using JavaScript. My main objective is to create a CSV file from this data. Here is an example of the file content: { Name:"nom1", Cities:[&apos ...

Swaying while navigating through volumetric fixed step raymarching

Encountering a bug with my shaders while working on the vertex: varying vec3 worldPosition; varying vec3 viewDirection; void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); worldPosition = vec3(modelMatrix * vec4 ...

Tips for extracting data from a PHP loop and displaying it in a div element

When I click on a PHP while loop, I want to change the value of a div. Here is my PHP code: <?php $query = mysql_query("select * from tbl_sub_product where product_id='$id'"); while($row=mysql_fetch_array($query)) { ?> <div>< ...

Storing Dark Mode Preference in Local Storage using JavaScript

I recently implemented dark mode on my website and it's working flawlessly. However, every time I refresh the page, it reverts back to the default Day Mode view. Is there a way to save these preferences? In the HTML section: <body> &l ...

JSON Novice - persistently storing data in JSON during browser refreshes

My AJAX poll was set up following a guide found here: http://www.w3schools.com/php/php_ajax_poll.asp Instead of storing the poll entries from an HTML radio button in an array within a text file as demonstrated in the tutorial, I wanted to save them in a J ...

Reformat a JSON file and save as a new file

I have a lengthy list of one-level JSON data similar to the example below: json-old.json [ {"stock": "abc", "volume": "45434", "price": "31", "date": "10/12/12"}, {"stock": "abc", "volume": "45435", "price": "30", "date": "10/13/12"}, {"stock": "xyz", "vo ...

Facing issues with Typescript imports for validatorjs?

Utilizing TypeScript with validator JS and encountering dependency issues: "dependencies": { "@types/validator": "^12.0.1", "validator": "^12.2.0" } Attempting to import isDividibleBy yields an error: import { isDivisibleBy } from "validato ...

Creating an event listener to conceal a popup with a click

One of the key elements in my project is a popup with the unique identifier of myPopup. The class show is responsible for toggling the display property from none to block, allowing the popup to appear on the screen. As a beginner in using event handlers, ...

Utilizing HTML Entities in jQuery

Is there a way to update the text of a submit button to display "Loading..." instead of "…" when clicked? Currently, I am encountering an issue where clicking the button still shows "…" instead of three dots. Below is the code snippet in qu ...

Issues arise when Angular and Jasmine are unable to inject a controller

I'm encountering difficulties initiating Jasmine and AngularJS. My attempt at creating a basic example is mainly based on the Angular docs: Within testme.js, I've established a module and a controller: (function(){ "use strict"; ...

Is it possible to trim a video using HTML code?

I am trying to find a way to crop a video using HTML 5. <video id="glass" width="640" height="360" autoplay> <source src="invisible-glass-fill.mp4" type="video/mp4"> </video> Currently, the video has a resolution of 640x360. However ...