Transform improperly formatted strings into a date data type

I need help converting this string to a date type in Typescript for sorting purposes:

31/10/2017 18:12:02

Using new Date() is not working (it returns Invalid Date), even when trying like this :

let date = moment(item1.sendedOn.toString()).format('DD/MM/YYYY h:mm:ss');
console.log(date.toString());

Any suggestions?

Answer №1

For ease of use, you can convert the date to ISO Format and then utilize new Date()

var dateStr = "2018-12-23 18:12:02".replace(" ", "T") + ".000Z";

console.log(new Date(dateStr).getTime());
// This allows for direct comparison after sorting 

Edit: (In case there is a / used as the date separator):

var dateStr = "2018-12-23 18:12:02".replace(/\//g, "-").replace(" ", "T") + ".000Z";

console.log(new Date(dateStr).getTime());

Answer №2

Why is my new Date() function giving me an Invalid Date error?

It's possible that the string you're using is not formatted correctly or contains hidden characters. In the example below, we create a new Date object with a properly formatted string and it works without throwing an error.

var result = new Date('2022-10-15 08:30:45');
console.log(result);

If this code snippet doesn't work in your browser, it could be a browser-specific issue.

Answer №3

To achieve the same functionality, one can utilize momentjs.

let date = moment("2019-01-15 12:05:30").format('MM-DD-YYYY');
console.log(date)
let dateObj = moment("2019-01-15 12:05:30").toDate();
console.log(dateObj)
<script type="text/javascript" src="http://momentjs.com/downloads/moment.min.js"></script>

If usage is required with typescript and angular2 framework:

npm install moment --save

import * as moment from 'moment';

providers: [{ provide: 'moment', useValue: moment }]

Answer №4

After incorporating moment.js, I managed to obtain the solution:

 const timestamp = moment(inputDate, 'DD/MM/YYYY h:mm:ss').format();

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

Choosing an array from the MongoDB database

{ "_id": "4f609932615a935c18r000000", "participants": [ { "user_name": "john1", "role": "user", "created_at": { "sec": 1331730738, "usec": 810000 }, { "user_name": "john2", "role": ...

Using ngForm to implement multiselect options in HTML

Attempting to implement a multiselect dropdown that is tied to a dynamic property receiving data from a JSON script via service. Successfully displayed the data in the dropdown, but encountering abnormalities when adding the multiple attribute within the s ...

Having trouble importing the named export `{module}` from a non-ECMAScript module with TipTap and Nuxt?

I'm using TipTap with Nuxt and running into some issues that I can't seem to resolve. Despite following suggestions from the repository's issues, I keep encountering these specific errors: ERROR in /Volumes/Projects/nuxt/candy-hub-lerna/no ...

Generating a new array in NodeJs from data retrieved by querying MySQL

In my NodeJs project, I am trying to generate a new array from the results of a MySQL query. Here is the current result: [ { "availabilityId": 1, "dayName": 1, "fromTime": "05:30:00", "toTime": "10:00:00" }, { ...

Creating a customized design for a React application with the use of Scss and JavaScript variables

Is there a method to incorporate JavaScript variables into an SCSS file? For instance, I have a JavaScript file containing the following code: // sky blue const PRIMARY_COLOR = '#489FEF' export { PRIMARY_COLOR} and I would like to utilize it ...

Creating consistent web page designs: A guide

Having created multiple practice websites, I have successfully published one. However, I am now faced with the challenge of needing to make design changes. If I want to modify the text surrounding a certain element in every page, I find myself having to ...

Mastering the art of handling errors with Javascript Promises

Through thorough research and some assistance, I have managed to create and annotate code that I believe will enhance the comprehension of Javascript Promises for individuals. However, I encountered a puzzling issue when attempting to trigger an error by ...

Implement CSRF protection for wicket ajax requests by adding the necessary header

I'm currently working on a website created with Apache Wicket and we're looking to enhance its security by implementing CSRF protection. Our goal is to keep it stateless by using a double submit pattern. For forms, we are planning to include a h ...

Limiting the input in a text box to only allow whole numbers and no decimal values

What is the best way to limit a textbox to only accept whole numbers and exclude decimal values and alphabets? ...

When using Webpack and Typescript together with the watch feature, an error with code TS2554 may occur only during

Software in use: webpack 4.8.3 typescript 2.8.3 ts-loader 4.3.0 Configuration for Webpack: rules: [ { test: /\.ts(x?)$/, exclude: /node_modules/, use: ['ng-annotate-loader', 'ts-loader'] }, . ...

Calculating the Mean of an Array in JavaScript

Greetings! I am working with an array that has the following structure: [ { group: "23", delays: [ { Station: "a", Arrival: "3", Departure: 0 }, { Station: "b", Arrival: -179, Departure: 0 }, ...

Guide on using a for loop to assign JSON data

I am currently developing a local weather widget for my website and have successfully integrated data using the OpenWeather Api. However, due to my limited experience in jquery/javascript, I am facing challenges in loading data for a 10-day forecast. Any a ...

Launch a new Windows form upon clicking an HTML button using DotNetBrowser

I attempted to open a Windows form using the DotNetBrowser control with specific HTML content as shown in the code below. Upon clicking a button on the HTML page, I want to hide the loaded form and then display the second Windows form. Here is the C# cod ...

Effortless loading with tab navigation in routers

Encountering an issue with router navigation and lazy loaded modules. When lazy loading is removed, everything works fine. Here is my setup specifically for lazy loaded modules: In the app.template file, I have the main router-outlet defined. The root ap ...

Angular 12 encounter: URL not recognized

When trying to send a request to https://jsonplaceholder.typicode.com/users, I keep encountering an error stating 'Invalid URL', even though the URL appears correct to me. This issue is quite puzzling to me. Error message : Message: Failed to ex ...

Javascript loop woes

I have a number array ranging from 1 to 20. My goal is to create a loop that extracts every nth element from the array, starting with (1, 6, 11, 16). After the initial loop, it should then extract every 5th element, starting from 2 (2, 7, 12, 17). My atte ...

Refine the search outcomes by specifying a group criteria

I have a scenario where I need to filter out service users from the search list if they are already part of a group in another table. There are two tables that come into play - 'group-user' which contains groupId and serviceUserId, and 'gro ...

Retrieving JSON using Javascript includes, why is there a difference in the time needed for the JS download and the start of JS execution?

During the optimization of my web application, I encountered a challenge with parsing JSON data in large quantities. The data consisted of up to 1000 objects with hundreds of attributes each, causing the eval function to take a significant amount of time t ...

Include Django CSRF token in an Angular 5 form

Currently, I am working on a Django-Angular5 project. I have a login form in Angular and I am facing an issue with adding a CSRF token to the form. Without it, I receive a Forbidden (403) error indicating that the CSRF verification failed due to a missing ...

Executing a callback function in AngularJS after dynamically rendering elements with `ng-repeat`

Many posts demonstrate how to implement callback functions in directives to wait for ng-repeat to finish before calling a function. Here is an example: <div ng-repeat="Object in Objects" class="objectClass" on-finish-render>{{Object.Overlay}</div ...