Anna
Anna

Reputation: 51

Convert the any locale Date to en-US locale date string

I have converted the application to German as regional Format and the locale_id is registered as I am able to see the expected date format. But as I have date shown in German Format which is 13.10.2020 (it uses "." special character and format is "DD.MM.YYYY")

When I select the date from date picker it gets selected as expected but while saving i have to convert the format in normal en-US locale for the data base to store.

For example - German as locale_ID -> Date format is DD.MM.YYYY But while saving I want to convert it in YYYY-MM-DD

I have tried following -

  1. FormatDate("DD.MM.YYYY", "shortDate", "en-US") of @angular/common but it throws an Invalid Date error
  2. moment("DD.MM.YYYY").format("YYYY-MM-DD") of moment.js but this gives me Invalid Date.

Could you help me that how exactly should i change the date to en-US locale without changing the locale_Id as I want the system in German only.

My system accepts almost all the locales so German to en-US is one of an example. So I am looking for some generic way to convert it.

Upvotes: 0

Views: 1106

Answers (1)

beingyogi
beingyogi

Reputation: 1416

You can try this with Moment.js

console.log(moment("02.04.2021", "DD.MM.YYYY").format('YYYY-MM-DD'));

    moment.locale(this.locale);
    if (!format) { format = "YYYY-MM-DD"; }
    var localeFormat = moment.localeData().longDateFormat('L');
    return moment(date, localeFormat).format(format);

Upvotes: 1

Related Questions