Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

 <td>{{suite.testSuiteAttributes && 
       suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd'
     }}
</td>

I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an error:

Unable to convert "2018-01-01-12:12:12:123456" into a date for the Pipe 'DatePipe'

I believe the issue stems from the fact that the timeStamp is not in the correct date format. The backend is only providing this specific date. Any suggestions on how to handle this?

Answer №1

It appears that the date format you are receiving from the server is incorrect. In order to convert it, you will need a valid date format.

To address this issue, I have created a workaround solution by implementing a myDateParser() method. This method can convert your invalid date into a valid one.

your.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  modifiedTimestamp;

 constructor(){

   // Passing unformatted date
   this.modifiedTimestamp = this.myDateParser('2018-01-01-12:12:12:123456');
 }

 /**
  * Custom Date parser

  */
  myDateParser(dateStr : string) : string {
    // Converting to a valid date format - e.g., 2018-01-01T12:12:12.123456;

    let date = dateStr.substring(0, 10);
    let time = dateStr.substring(11, 19);
    let millisecond = dateStr.substring(20)

    let validDate = date + 'T' + time + '.' + millisecond;
    console.log(validDate)
    return validDate
  }
}

your.component.html

  <table>
    <tr>
     <td>{{modifiedTimestamp |  date: 'yyyy-MM-dd'}}</td>
    </tr>
   </table>

View the solution on stackblitz

I hope this solution proves useful for you!

Answer №2

It appears that the date "2018-01-01-12:12:12:123456" you provided is not in the correct format according to ISO 8601 standards, therefore it cannot be processed by the default parser. You will need to either input a valid date format or create a custom parser.

You have the option of using regex or utilizing string manipulation functions such as substring, as shown in another answer.

In Javascript, dates are displayed in the local time zone of the user's browser, which corresponds to the system time of the user. There isn't a built-in method to create a date in a different timezone. To work with UTC and convert it to a specific timezone, you can utilize the toLocaleString() method. This process will only be accurate if the date received from the backend is in CT (Central Time) timezone.

let result = "2018-01-01-12:12:12:123456".match(/(\d{4})-(\d{2})-(\d{2})-(\d{2}):(\d{2}):(\d{2}):(\d{3})/).map(x => parseInt(x, 10));

result.shift();

console.log(new Date(...result).toLocaleString())

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

Quick method to assign child iframe title as index.html <title>title</title>

Is there a simple method to dynamically update the <title> of my index.html based on the <title> of a child iframe? Take a look at my website for reference If the content within the iframe changes, will the title automatically update along wi ...

Creating a feature in Vuejs that allows for real-time card updates on the screen by sending a post request to the database and

After sending a post request to the database, I need to refresh my cardData array which gets its value from a get request in order to see the changes. The current saveDraft() function adds values to the cardData array, but it requires a page refresh or c ...

Why is JavaScript globally modifying the JSON object?

I have a few functions here that utilize the official jQuery Template plugin to insert some JSON data given by our backend developers into the variables topPages and latestPages. However, when I use the insertOrHideList() function followed by the renderLis ...

Increase the bottom padding or add some extra space to the Bootstrap form or page

I am currently working on enhancing a Bootstrap Form that includes reset/submit buttons positioned at the bottom. A common issue is when iPhone users attempt to click the Submit button, which initially displays Safari icons before requiring an extra tap to ...

Using Angular2 translate in expressions: a step-by-step guide

Looking at the code below, you'll notice that starting from line 44, the titles are already enclosed within {{}} expressions: import { Component, ViewChild } from '@angular/core'; import { Events, MenuController, Nav, Platform } from ' ...

Ways to clear an Angular form after a failed login attempt

Looking for a solution to reset the input fields used to store login PIN from a user. My current code generates a modal error message but I am facing an issue in resetting the PIN input fields under the #inputs id. Take a look at the code snippet below: H ...

Python is experiencing difficulties with copying xpath elements

I attempted to utilize some Python code to access Twitter and retrieve the "Happening now" text. Unfortunately, it was unsuccessful. import webbrowser print("Visiting Twitter.com...") webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/c ...

Angular Github Deployment Issue: Page malfunctioning as a result of strict-origin-when-cross-origin restriction

I am currently learning Angular and attempting to deploy it on Github Pages. However, I have encountered an issue where the app is not functioning properly. After inspecting the page, I discovered a CORS origin error when trying to access certain resource ...

Show or hide a component based on a mouse click in Vue JS

After a prolonged absence from working with Vue JS, I find myself in the process of displaying a list of data with a button for each item. The goal is to conditionally render a component when a button is clicked. I am wondering if there is a recommended a ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

What is the best way to incorporate a unique font with special effects on a website?

Is there a way to achieve an Outer Glow effect for a non-standard font like Titillium on a website, even if not everyone has the font installed on their computer? I'm open to using Javascript (including jQuery) and CSS3 to achieve this effect. Any sug ...

Incorporating user input into a form using NodeJS and Angular

I am currently facing an issue while trying to add a new entry using NodeJS with an Angular form. Every time I click on create, the data is not being inputted into the database. To address this, I included the angular.toJson function to convert the input i ...

What are the steps for incorporating a Zoom & Pan feature into an anyChart SeatMap?

In our IONIC application, we are utilizing the anyChart SeatMap to display SVG-based seatmaps. However, some of the seatmaps are quite large and we require support for zooming and panning functionalities. Despite researching the 'Move & Zoom' opt ...

What could be causing Next.js to re-render the entire page unnecessarily?

As a newcomer to Next.js, I am trying to develop an app where the header/navbar remains fixed at all times. Essentially, when the user navigates to different pages, only the main content should update without refreshing the navbar. Below is the code I have ...

How can we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

Updating the image source through ajax by retrieving the location from the database

Is there a way to dynamically change the image source using AJAX? I have the location saved in my database and I want to set the img src from the value of something like data[0]['patient_photo']. Below is the HTML code for the image: <img id= ...

Leveraging ng-change in AngularJS when utilizing the "Controller As" syntax

Attempting to steer clear of using $scope within my controller function, I have instead chosen to use var viewModel = this; employing the "controller as" viewModel syntax. The issue at hand is that while I can access data from a service, invoking functio ...

Is there a different option available in place of the JavaScript confirm function?

I developed an application where I heavily utilized the javascript confirm function. confirm("Do you want to proceed"); However, I am not satisfied with the default appearance of the confirm dialog and would like to implement a customized version with be ...

Using the onclick attribute as a unique identifier for a button

I am currently facing a challenge with a form that does not have an ID Here is the code snippet in question: <button class="btn btn-primary" onclick="showModal()" type="button">Browse Data</button> Unfortunately, I don't have any contro ...

Issues with debuggers in Chrome and Firefox with AngularJS are causing frustration for developers

Currently, I am in the process of developing a hybrid application that combines AngularJS with Angular 8. As part of my testing procedure, I am attempting to debug the application. However, I have encountered an issue where the debuggers function properly ...