Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to Date class type in angular 4

I have a string as follows in my .ts file.

const date = "5/03/2018";

I want to convert to the date type which is default date type returned by angular Date class.

 Tue Apr 03 2018 20:20:12 GMT+0530 (India Standard Time)

Now I have to convert this string type date to default angular date type.Any help? I have tried the following.

const date1 = new Date("5/03/2018");

but it is not working i am not getting the required format. this is stackblitz link any suggestions would be helpful. https://stackblitz.com/edit/angular-gdwku3

like image 859
roopteja Avatar asked Apr 03 '18 15:04

roopteja


2 Answers

Change the date format to YYYY-MM-DDformat creating the date object.

var date = new Date ("2014-10-10"); console.log(date.toDateString());

Remember to call the toDateString method.

like image 92
michaelitoh Avatar answered Sep 26 '22 07:09

michaelitoh


Check out this function(stackblitz), it will format the date comming in different formats and you can play with the year, month and day places as you wish:

  parse(value: any): Date | null {
    if ((typeof value === 'string') && (value.includes('/'))) {
      const str = value.split('/');

      const year = Number(str[2]);
      const month = Number(str[1]) - 1;
      const date = Number(str[0]);

      return new Date(year, month, date);
    } else if((typeof value === 'string') && value === '') {
      return new Date();
    }
    const timestamp = typeof value === 'number' ? value : Date.parse(value);
    return isNaN(timestamp) ? null : new Date(timestamp);
  }
like image 45
Lucas Avatar answered Sep 22 '22 07:09

Lucas