chris01
chris01

Reputation: 12321

Parse a date with DatePipe

I am using a datepipe to convert a Date into a string.

var mydate : Date = new Date ();

That works in the template

{{ mydate | date: "dd.MM.yyyy" }}

as well as in the class

 let str : string = this.dp.transform (dtm, "dd.MM.yyyy");

Is there a way to do the reverse? So the pipe should parse a string and gets me a Date.

Upvotes: 2

Views: 3379

Answers (4)

luiscla27
luiscla27

Reputation: 6409

For me, library moment was the best and consistent alternative to do this, just install the dependency and use it directly.

npm install moment

And simply at your code:

import * as moment from 'moment';
...
public parse(stringDate: string, stringFormat: string, lang: string): Date {
    try {
      const dateMoment = moment(stringDate, stringFormat.toUpperCase(), lang, true);
      if (dateMoment && dateMoment.isValid()) {
        return dateMoment.toDate();
      }
      return null;
    } catch (e) {
      console.error('Error while parsing date', stringDate, e);
      return null;
    }
}

Later you can just use:

this.parse('2020-08-09', 'yyyy-MM-dd', 'en');

Upvotes: 0

chris01
chris01

Reputation: 12321

So formatting and parsing is not natively possible. I did it with JavaScript RegExp to parse the date by myself. Another alternative would be moments.js but I did not use that.

<input type="text" placeholder="DD.MM.YYYY" [value]="mydate | date: 'dd.MM.yyyy'" (change)="setDate ($event)"/>


setDate (e)
{
  let val : string = e.target.value;

  let rgx : RegExp = new RegExp ("^([0-9]{2})\.([0-9]{2})\.([0-9]{4})$");   // DD.MM.YYYY

  let match : Array <string>  = rgx.exec (val);
  if (match != null)
  {
    this.selday = new Date (Number (match [3]), Number (match [2]) - 1, Number (match [1]));
    this.requestData ();
  }
}

Upvotes: 2

Douglas P.
Douglas P.

Reputation: 560

The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

var unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');

console.log(unixTimeZero);
// expected output: 0

console.log(javaScriptRelease);
// expected output: 818035920000

Date.parse docs here.

Upvotes: 1

Youssef Tounoussi
Youssef Tounoussi

Reputation: 464

Yes! you can create your own Pipe that implements the PipeTransform.

Please look at this : https://ultimatecourses.com/blog/angular-pipes-custom-pipes

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'stringToDate' })
export class StringToDate implements PipeTransform {
  transform(stringDate: string) {
    // Do the conversion, Formating, substring ... here
    let newDate = new Date(stringDate);
    return newDate ;
  }
}

Import this Pipe into your ngModule, and use it in the Template

Upvotes: 2

Related Questions