Data string not being converted correctly to date format

Here is a table I am currently working with:

ID    DateColumn

1     3/7/2019 5:29:38 AM
2     3/8/2019 5:28:38 AM
3     3/7/2019 5:30:38 AM
4     3/7/2019 5:31:38 AM

The date column in this table is being processed as a string when bound to the grid. To effectively sort the data, I need to convert these strings into dates.

I have attempted to write code for this task:

getServiceResults() {

    this.serviceCheckService.getResults(Appconfig.PageSize, Appconfig.PageNo).takeUntil(this.ngUnsubscribe).subscribe((data) => {

    this.resultData = data; 
            this.resultData.forEach(x => x.DateColumn = new Date(x.DateColumn)); 

      });
  }

Unfortunately, the above code is producing a syntax error. Can you provide guidance on how to properly convert each value in the date column from a string to a date, and then proceed with sorting that column?

Answer №1

Give this line a try without utilizing the replace method.

this.resultData.forEach(x => x.DateColumn = new Date(x.DateColumn)); 

If you want to sort the data, you can use the following code:

resultData.sort((item1, item2) => { if(new Date(item1) < new Date(item2)) {return 1} else return -1;} )

Answer №2

Your date format is set to American, which uses MM/DD/YYYY. You can input it directly into the constructor. (This isn't an ideal format since many countries use DD/MM and it's not always clear just by looking at it. Have you considered sending it in ISO format instead?)

When you have an array of objects, each containing a date property, follow these steps...

myArray.sort((a,b) => a.dateColumn.getTime() - b.dateColumn.getTime())

Answer №3

Assuming the date format is in MM/DD/YYYY, you can easily convert all date strings to a Date type for sorting purposes.

// Convert string dates to Date objects
this.dataList.forEach(item => item.date = new Date(item.date));

// Sort the data based on date
this.dataList.sort((a, b) => a.date.getTime() < b.date.getTime() ? 1 : -1);

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

Having trouble accessing the value of an <asp:HiddenField> using javascript

Currently, I am setting a value to a hidden field and attempting to retrieve that value in my JavaScript code. In the declarative part of my code: <asp:HiddenField ID="chkImages" runat="server" /> <div id="main" runat="server" style="display:non ...

Exploring different pages in an Ionic and AngularJS mobile application

I am brand new to the world of Ionic and AngularJS. I have just started working on a simple project but have hit a roadblock. My goal is, To create a login page and a register page. When a user clicks the register button on the login page, they should be ...

Trouble with Bootstrap Popover's visibility

My current setup involves a popover that is not initializing properly. The code I am using is shown below: HTML: <div data-toggle="popover" data-placement="bottom" data-content="xyz">...</div> JavaScript: $(function () { $('[data-t ...

After loading the ajax content, remember to include the JavaScript files

Here's the situation: I am importing some php files, one of which includes a slider that requires .js files. However, when I make an ajax call, the file is imported but the js files are not. Is this normal behavior? I attempted the following: var s ...

Personalized information box utilizing Reactive Extensions in JavaScript

I am currently working on implementing a custom tooltip for a diagram using the vis-network library and RXJS. The key concept is to have: An observable named diagramElementHover$ to display the tooltip An observable named hideTooltipObs$ to hide the too ...

Unable to reset the HTML5 slider successfully

Despite multiple attempts, I have finally reached out for assistance. Here is the code snippet for my slider: <input autocomplete="off" type="range" min="0" max="100" value="50" class="myslider" id="mysliderID-slider" data-fieldid="something"> <i ...

Tips for utilizing a shared controller in an Angular Material popup dialogue

Within my project, Angular Material is being used for various dialogs, primarily for alert purposes. However, I now find myself in need of a more complex dialog. The example provided on the Angular Material site showcases how to create a dialog: function ...

Example TypeScript code: Use the following function in Angular 5 to calculate the total by summing up the subtotals. This function multiplies the price by the quantity

I have a table shown in the image. I am looking to create a function that calculates price* quantity = subtotal for each row, and then sum up all the subtotals to get the total amount with Total=Sum(Subtotal). https://i.stack.imgur.com/4JjfL.png This is ...

What could be causing my second ajax call to render the page unresponsive?

I am encountering an issue with my AJAX call. It works fine on the first attempt, but when I try to call it a second time, the page becomes unresponsive. I am not sure what is causing this issue. The code is located within the document ready function. The ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

Condense items into objects and arrays when the Express query yields multiple objects in a many-to-many query

I have a situation where my SQL queries are returning multiple objects due to a many-to-many mapping in express. I am in search of a tool that can help me simplify these common objects by nesting arrays of objects within them. SELECT * FROM User LEFT JOIN ...

Use Object.assign to swap out the current state with a new

Why does the React component with state { key: bool } not omit the existing state key from the new state when a different option is clicked? Link to the code var SampleComponent = React.createClass({ getInitialState: function() { return {}; }, ...

Timepicker Bootstrapping

I've been searching for a time picker widget that works well with Bootstrap styling. The jdewit widget has a great style, but unfortunately it comes with a lot of bugs. I'm on a tight deadline for my project and don't have the time to deal w ...

Transfer the unique field name to a universal assistant

Consider the code snippet provided in this playground: class A { private z = 0 } type K = "z" type ValidKeys = A[K] extends any ? K : never The type ValidKeys compiles correctly and matches K only when K represents a subset of keys from A. It ...

Copy the content of one input field into another field at the same time

I have encountered an issue that seems simple, yet the proposed solutions have not been effective. Most suggestions involve using jQuery, but Bootstrap 5 has shifted away from jQuery. I am looking for a solution using JavaScript or HTML only. The problem ...

Retrieving the text value of a selected option with a reactive form

This is my select option HTML <select _ngcontent-c3="" formcontrolname="role" value="" ng-reflect-name="role"> <option _ngcontent-c3="" value="addrole" ng-reflect-value="addrole">--Add Role--</option> <option _ngcontent-c3="" v ...

Customizing MUI V5 Variants

I'm having trouble customizing the variant options in MUIPaper, and I can't figure out what mistake I'm making. The available types for the component are: variant?: OverridableStringUnion<'elevation' | 'outlined', Pape ...

Initiate modal from sub-component

Right now, I am developing a vue application with a structure that closely resembles the following: <div class="characters"> <Character v-for="character in this.charactersToSearch" :key="character.id" :name="cha ...

Which comes first in AngularJS: ng-include or ng-repeat?

What is the outcome if I have a template containing ng-repeat and include it using ng-include? Will the included template have the completed ng-repeat, or will it be included without the ng-repeat being complete (and then completed after inclusion)? ...

The CSS "mask" property is experiencing compatibility issues on Google Chrome

Hey there! I've recently developed a unique progress bar component in React that showcases a stunning gradient background. This effect is achieved by utilizing the CSS mask property. While everything runs smoothly on Firefox, I'm facing a slight ...