1

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

1
  • 2
    please try this. new Date(Number(Date.parse(data.value))) Commented Sep 4, 2019 at 9:12

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I had tried this already as well, but Date.parse() return a number, which is not a Date; And new Date(Date.parse(data.value)) doesn't work either I'm just super bad when it comes to dates manipulation :<
1

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);

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.