The json response is not properly displaying the date formatting

I recently received a JSON response that includes dates that need to be formatted. Here is an example of the data:

{
    "webservice_status": {
        "status": "SUCCESS",
        "message": ""
    },
    "informationList": [{
        "TestNumber": "12",
        "Color": "RED",
        "dateOfPaint": "10242016",
        "location": "Wall"
    }, {
        "TestNumber": "13",
        "Color": "BLUE",
        "dateOfPaint": "10232016",
        "location": "Floor"
    }, {
        "TestNumber": "14",
        "Color": "GREEN",
        "dateOfPaint": "1052016",
        "location": "Wall"
    }, {
        "TestNumber": "15",
        "Color": "BLACK",
        "dateOfPaint": "10232016",
        "location": "Wall"
    }]
}

After attempting to use Moment.js to format the dates, I encountered an issue where the date was returning as Invalid Date. Here is the code snippet with the problem:

this.processJSON = function (data_, textStatus_, jqXHR_){
    var dateMoment = data_.informationList[0].dateOfPaint;
    console.log("The date we are testing:" + dateMoment);
    console.log(moment(dateMoment).format('MM/DD/YYYY'));
}

Given this situation, I am considering if it's possible to manually add slashes to the date string such as 10242016, transforming it into 10/24/2016, without using Moment.js. However, I would need to account for cases where the dates already have slashes and are in the correct format within the JSON response.

Answer №1

moment(String) function can handle strings that adhere to the ISO 8601 and RFC 2822 formats:

When converting a string into a moment object, it first checks if the string matches recognized ISO 8601 formats, then validates against the RFC 2822 date-time format. If neither match, it resorts to using new Date(string).

If your input string does not conform to a known format, you should specify the format when using the moment parser (moment(String, String)).

If you are uncertain about the exact format of an input string, but have some possible options, you can provide an array of formats.

For instance, if your data may include slashes ("/"), you can utilize moment(String, String[]) with ['MMDDYYYY', 'MM/DD/YYYY'] as the second parameter.

To display the value stored in the moment object, use the format() method. With format(), any invalid inputs like 1052016 will result in "Invalid Date," indicating inconsistencies (e.g., October does not have a 52nd day). You can verify the validity of the moment object representing a date/time by employing isValid().

Here is a practical example:

var data_ = {
    "webservice_status": {
        "status": "SUCCESS",
        "message": ""
    },
    "informationList": [{
        "TestNumber": "12",
        "Color": "RED",
        "dateOfPaint": "10242016",
        "location": "Wall"
    }, {
        "TestNumber": "13",
        "Color": "BLUE",
        "dateOfPaint": "10232016",
        "location": "Floor"
    }, {
        "TestNumber": "14",
        "Color": "GREEN",
        "dateOfPaint": "1052016",
        "location": "Wall"
    }, {
        "TestNumber": "15",
        "Color": "BLACK",
        "dateOfPaint": "10232016",
        "location": "Wall"
    }]
}

var processJSON = function (data_,textStatus_,jqXHR_){
  for(var i=0; i<data_.informationList.length; i++){
    var dateMoment =  data_.informationList[i].dateOfPaint;
    console.log("The date we are testing:"+dateMoment);
    console.log(moment(dateMoment, ['MMDDYYYY', 'MM/DD/YYYY']).format('MM/DD/YYYY'));
  }
}

processJSON(data_);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Answer №2

To transform the string "10242016" into a date format with slashes such as "10/24/2016", you can utilize the .replace() method along with a regular expression pattern like this:

var formattedDate = inputString.replace(/^(\d{2})(\d{2})(\d{4})$/, "$1"+"/"+"$2"+"/"+"$3");

Example:

var inputString =  "10242016";

var formattedDate = inputString.replace(/^(\d{2})(\d{2})(\d{4})$/, "$1"+"/"+"$2"+"/"+"$3");
console.log(formattedDate);

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

Strengthening the security of PHP using JSON

I'm working on a PHP script that receives data from an Android application. What security measures should I implement to ensure the safety of this script? Are functions like isset enough? <?php require ('config.php'); $connection=mysqli ...

What is the best method to update the content of a bootstrap-5 popover using only pure JavaScript?

Having trouble changing the content of a Bootstrap popover using vanilla JavaScript? The code seems to be updating, but the changes are not reflecting on the site. Any suggestions or alternative methods would be greatly appreciated! Maybe there's a di ...

Having difficulty converting a local variable into a global variable in JavaScript and Express

I am facing challenges trying to convert a local variable into a global variable while working with Express and Javascript. Below is my JavaScript code snippet: // Setting up Express and EJS const express = require("express"); const JSON = requi ...

Transforming CSV data into a particular JSON structure using PHP

I currently have a PHP script that converts CSV data to JSON format, but I am looking to modify the structure of the output JSON. Here is an example of my CSV data: Icon Name, Responses, Performance 03_v10_Assembly_point, 225, 38 55_v10_Fire, 203, 87 ...

Navigate down to the lower section of the webpage once the fresh container has finished loading

Let's get straight to the point.. I have got 2 containers, each with a height of 100vh. The second container is supposed to be displayed when a button in the first container is clicked. However, the issue arises when the button click event function al ...

Error in React.js: Attempted to register component with a target container that does not exist in the DOM

Hey there, I'm facing an issue that says: main.js:808 Uncaught Error: _registerComponent(...): Target container is not a DOM element. I checked out this question, but I can't seem to pinpoint what exactly I'm doing wrong. Below is the cod ...

Angular has reached the limit of 10 $digest() iterations while trying to create a deep copy of an array. As a

I am aiming to design a table with filters in the table header. The filter should display a list of unique values in each column. Below is a simplified version of the code: <table> <tr> <th class="dropdown" ng-repeat="field in data ...

Which JSON JavaScript polyfill stands out as the top choice?

I'm currently in search of a JSON polyfill to enable JSON support on older browsers for my JavaScript code. After some research, it seems like JSON2 and JSON3 are popular choices, with JSON3 being positioned as an upgrade over JSON2. However, I'm ...

Compiling Typescript with module imports

In my project, I am working with two files named a.ts and b.ts. The interesting part is that file b exports something for file a to use. While the TypeScript compiler handles this setup perfectly, it fails to generate valid output for a browser environment ...

Abrupt surge in Firestore read operations detected in Next.js application following a period of no modifications - refer to the accompanying visual

https://i.sstatic.net/vim7m.png During the initial 10 days of working on the project, I noticed a consistent range of reads between 100 - 300 per day while regularly refreshing documents from firestore. Days 11-15 were spent away from the project visiting ...

Tips for categorizing items retrieved from .getJSON based on their category property

Looking to display a menu of coffee items with their respective parent categories on the page? Here's how you can start: Category Title Item Item Item Item Category Title Item Item This is what my data model looks like: { "menuItems": [ ...

Send a variable to a specific page and locate it within a dropdown menu

I am currently working on an HTML page that displays employee leave details. The page includes a pending leave option with the ability to edit. Users should be able to edit their leave while it is still marked as PENDING. Once the edit button is clicked, t ...

Which structure is more effective or accurate for JSON formatting: using arrays?

I am seeking information about the JSON format in relation to SQL results. Year SumOfYear 2011 0.30 2012 0.19 update The following is a snippet of PHP code. while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { $results[] = array( '"Yea ...

Vue Array Proxy Class Fails to Trigger Reactivity

My custom Array extension has a feature where it intercepts changes made to its properties using Proxy, which is returned from the constructor. However, when used in a Vue component, it encounters issues. For example, when a filter is added, the display do ...

What causes the inversion of height and width settings in react-webcam?

Currently utilizing react-webcam with the following configuration. <Webcam audio={false} screenshotFormat="image/jpeg" videoConstraints={{ facingMode: "environment", width: camera ...

How can we effectively share code between server-side and client-side in Isomorphic ReactJS applications?

For a small test, I am using express.js and react.js. Below you can find my react code: views/Todo.jsx, var React = require('react'); var TodoApp = React.createClass({ getInitialState: function() { return { counter: 0 ...

Persist JSON data to Django models

image Can someone help guide me on how to save JSON data to models efficiently? I've tried using URLs but haven't been able to achieve the desired results. Any suggestions or methods would be greatly appreciated. Whenever I attempt to use the GET ...

Setting up environments utilizing restify

Having experience with gulp, I am well-versed in setting up a distinct configuration for each environment within a single configuration file. This allows for running gulp dev to initiate the server using the development environment configuration, gulp stag ...

Validating JSON schema with oneOf containing an array of mixed object types

I've been working on creating a JSON schema that includes an array of mixed object types. My approach involves utilizing the oneOf keyword, but it appears that there might be something missing in my implementation since my JSON data isn't validat ...

Postman is encountering issues with validating the JSON schema, despite the data being considered valid

Struggling to validate a response against a JSON schema? Even if the schema is valid, it always seems to fail. Let's take a look at the JSON data and the validation code in Postman: { "items": [ { "uuid": "f68ad4ba-a11e-485d-a ...