5

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

2 Answers 2

7

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.

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

6 Comments

Miachel can we do something like this var date = new Date("06/06/2018","yyyy/mm/dd"); to convert the string date to required format. Because the date string is from backend.
You can split your current date format and change to the one i've told you.
Does my last comment help? @roopteja
trying still will update if it works. Do you know anything that converts format directly through a function or property named .Format() like that
You can use moment.js for that. I've used it and it is awsome.
|
6

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

2 Comments

We can add a parameter about actual format and expected format and based on that decide if year is in the start or end. Right now its hardcoded inside the function
Right, PO should work with year, date, month values to format date as needed, its pretty straight forward and if he gets the date from server he might not even need an extra parametter, simply re arange values from value.split

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.