2

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
chris01
  • 10,921
  • 9
  • 54
  • 93

4 Answers4

2

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

RobC
  • 22,977
  • 20
  • 73
  • 80
2

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 ();
  }
}
chris01
  • 10,921
  • 9
  • 54
  • 93
1

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.

RobC
  • 22,977
  • 20
  • 73
  • 80
Douglas P.
  • 560
  • 4
  • 19
0

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');
luiscla27
  • 4,956
  • 37
  • 49