retArdos
retArdos

Reputation: 135

Convert string to date in Angular 8

In my angular component let's say that i have this string '16/12/2020 12:30:00' (french format).

How can I convert this to an Date object in the component ?

expiration_date: Date;
ngOnInit() {

   this.dateService.getOne('EXP_DATE').subscribe((data) => {
      this.expiration_date = new Date(data.value);
   });

    console.log(this.expiration_date);
}

I've tried formatDate as well as DatePipe but i get the following message:

"Unable to convert '16/12/2020 12:30:00' into a date".

undefined

Upvotes: 1

Views: 30135

Answers (3)

MoxxiManagarm
MoxxiManagarm

Reputation: 9134

Try the following

expiration_date: Date;
ngOnInit() {

   this.dateService.getOne('EXP_DATE').subscribe((data) => {
      this.expiration_date = Date.parse(data.value);
      console.log(this.expiration_date);
   });
}

Edit: The reason likely lies within your date format`

Note: Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Upvotes: 2

Tiep Phan
Tiep Phan

Reputation: 12596

install date-fns and using parse function:

import { Component } from '@angular/core';
import { parse } from 'date-fns';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  date: Date = null;
  ngOnInit() {
    const data = {
      value: '16/12/2020 12:30:00'
    }
    this.date = parse(data.value, 'd/M/yyyy HH:mm:ss', new Date());
  }
}

Demo: https://stackblitz.com/edit/angular-nlsuny

Upvotes: 1

Nirali
Nirali

Reputation: 514

I think first you have to split your date string to convert it into Date object, something like below (you can put below logic into separate function to handle date manupulation)

let dateString='16/12/2020 12:30:00';

let date=dateString.split(' ');

const dateObj=new Date(date[0].split('/')[0],date[0].split('/')[1],date[0].split('/')[2],date[1].split('/')[0],date[1].split('/')[1],date[1].split('/')[2]);

console.log('dateObj::',dateObj);

Upvotes: 1

Related Questions