Parsing an entire JSON array using Moment JS and formatting numerous instances of dates

I am working with an array of JSON objects retrieved from my MVC controller. These objects contain date fields that I need to parse and format.

By using the Newtonsoft.Json library in place of the default MVC JSON serialiser, my dates are already formatted nicely when they come back like this:

"SystemDate": "2013-05-06T17:19:40.443",
"LocalDate": "2013-05-06T18:19:40",

To handle these dates on the client side, I am utilizing Moment.js for date manipulation. I've been exploring ways to further format these dates for display purposes.

Instead of creating a custom function, which would take a JSON array of objects with dates to format along with specific field names and a date pattern, I'm considering if there is a built-in functionality in Moment.js that might achieve this more efficiently.

The proposed function signature would resemble something like:

function formatDates(dataArray, pattern, fields) { /code/ };

The dataArray structure could be similar to:

[{"name": Jammer, 
  "SystemDate": "2013-05-06T17:19:40.443", 
  "LocalDate": "2013-05-06T18:19:40"
 }, 
 {another object}
 {another object} 
 {another object}
]

A sample pattern might look like:

"dddd, MMMM Do YYYY, h:mm:ss a"

And the list of fields would be (using the provided example object):

[{"SystemDate"}, {"LocalDate"}]

While I am still relatively new to Moment.js and its API, I have not found any existing functionality within it that caters to this specific requirement after reviewing the documentation.

Before proceeding with implementing my custom function, I wanted to inquire if there are any features in Moment.js that could potentially streamline this process or if there are any suggestions on the best approach to accomplish this task?

Answer №1

When it comes to working with date manipulation libraries, the onus is often on the user to decode the data, iterate through it to find dates, utilize moments for formatting, and then encode the data back into the desired format. Despite this, the task at hand seems relatively straightforward.

The following snippet should help you achieve your goal:

Javascript

var jsonString = '[{"name":"Jammer0","SystemDate":"2013-05-06T17:19:40.443","LocalDate":"2013-05-06T18:19:40"},{"name":"Jammer1","SystemDate":"2013-05-06T17:19:40.443","LocalDate":"2013-05-06T18:19:40"},{"name":"Jammer2","SystemDate":"2013-05-06T17:19:40.443","LocalDate":"2013-05-06T18:19:40"},{"name":"Jammer3","SystemDate":"2013-05-06T17:19:40.443","LocalDate":"2013-05-06T18:19:40"}]';

var formatted = JSON.stringify(JSON.parse(jsonString).map(function (record)  {
    var requiredPattern = "dddd, MMMM Do YYYY, h:mm:ss a";

    record.SystemDate = moment(record.SystemDate).format(requiredPattern);
    record.LocalDate = moment(record.LocalDate).format(requiredPattern);

    return record;
}));

console.log(formatted);

View the result on jsfiddle

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

Is it possible for me to create a list in alphabetical order beginning with the letter B instead of A

My task involves creating a summary of locations using the Google Maps API. The map displays letters corresponding to different waypoints, and I have a separate <div> containing all the route information. Currently, I have the route information stru ...

What is the best way to access elements in a grid-view using JavaScript?

I am trying to incorporate a date-picker bootstrap onto a text box that is located inside a gridview. I cannot seem to figure out how to access the text box within the gridview as I keep getting an error message saying 'txtStartDate does not exist&apo ...

The mongoose library requires JSON input, yet it is unable to generate a dynamic JSON object from a Node

This question delves more into javascript and JSON concepts rather than focusing on the mongoose library. When working with Mongoose, conditions are expected to be in JSON format, like so: { $or: [ { "doc_no" : /first/i }, { "doc_type" : /second/i } ] ...

Create an animated effect using JavaScript to toggle the classList

As I delved into the world of CSS and HTML, I stumbled upon an interesting tutorial for creating a responsive navbar. You can check it out here. The tutorial showcases the mobile version of the navbar using the javascript function classList.toggle. I was ...

What is the true appearance of Ajax?

After spending a few days researching Ajax to use with the Django Python framework, I came across numerous resources on the topic. 1. function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyStat ...

Veracode Scan finds vulnerability in jQuery html method with Improper Neutralization of Script-Related HTML Tags in a Web Page error

Veracode has flagged the issue Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) within the following line of code. $('#SummaryDiv').html(data); $.ajax({ url: 'Target_URL', type: &a ...

Loop through the JSON array and append every value to the list within AngularJS

I'm just starting to learn about Angular JS and I have a question. I receive a JSON array as an AJAX response from a PHP page. I want to iterate through this JSON array and push each value into a list like this: angular.forEach($scope.companies.area, ...

What is the best way to implement component lazy loading in Preact?

My objective is to create two bundles during the build process, one for the index.tsx file and another for the lazy.tsx file. I am confident that there are one or two options that I am overlooking. Check out the example project on GitHub - example project ...

In order to successfully utilize Node.js, Async.js, and Listeners, one must ensure

Here is the log output from the code below, I am unsure why it is throwing an error. It seems that the numbers at the end of each line represent line number:char number. I will highlight some important line numbers within the code. Having trouble with t ...

checkboxfor allowing model to be bound for ajax postback

I am encountering an issue where my checkboxfor values are not being recognized as checked in my controller during ajax postback, even though they appear checked on the view before clicking the button control. Here's a snippet of my code: [HttpPost] ...

JavaScript not functional, database being updated through AJAX calls

I have created a game using Phaser, a JavaScript library for games. Now I am looking to implement a score table using JS/PHP. My main focus is on transferring a variable from JS to PHP in order to update the database. I have researched numerous topics and ...

Move a div by dragging and dropping it into another div

Situation Within my project, there is a feature that involves adding a note to a section and then being able to move it to other sections, essentially tracking tasks. I have successfully implemented the functionality to dynamically add and drag notes with ...

Is there a way to save a Vue file as a PDF in Vue.js?

I am looking for a way to enable users to download a Vue file as a PDF when they click on a button in the main component. Any suggestions on how to achieve this would be greatly appreciated. download.vue <template> <div> This file contai ...

Exploring the outer scope within JavaScript

Currently, I am working on a JavaScript code snippet where I am attempting to set the 'obj' variable from the success and error callbacks. However, it seems like the scope of the 'toLinkInfo' function is not encompassing these callbacks ...

Using jQuery, create a variable that combines a text string with a

I have a list with custom bullet icons that I need help modifying using JavaScript. Specifically, I am looking for a script that can identify if the icon name is followed by a number and then add an image tag with a class based on that icon number for each ...

identifying the element targeted on dynamically created links with the help of jquery

I have created dynamic links where clicking on a country link displays the cities of that particular country. I am trying to retrieve the event.target.id of the dynamically generated city link when it is clicked. $(".countryName").children().on('cl ...

Node.js always returns an empty req.body

const server = express(); server.use(express.json()); server.use(express.urlencoded({ extended: true })); server.post("/", (req, res) => { res.status(200).json(req.body); }); receiving empty object consistently I am utilizing Thunder ...

Using Angular promises and the $http service

ng.module('app') .service('CardService', ['$http', CardService]) function CardService($http) { this.$http = $http; var self = this; $http.get('http://localhost:3000/db').success(function(data) { ...

What procedures should I follow to transition from my pygame client to a browser-based game?

After developing a game server in Python to connect with multiple clients using Pygame via sockets, I realized that the turn-based card game I created doesn't require a lot of data flow since it's in JSON format. To avoid the need for clients to ...

Encountering an isObject issue while using the @material/core package

When attempting to run the project, I encountered this error in the console: isobject error Upon inspecting the package-lock.json file, I discovered that the isobject dependency was missing in @material-ui/core. Adding it manually resolved the issue. pac ...