Yaden Mustopa
Yaden Mustopa

Reputation: 11

how to convert date string to date use javascript moment.js

how to convert date string : example : with format "dd M yyyy" => "07 Okt 2020" wont to date "2020-10-07"

Upvotes: 1

Views: 100

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30675

We can parse after setting the moment locale to German, this includes a tweak to exclude the period from short month names.

For example:

// We must set the months up to exlude the trailing period "." so we parse our date correctly.
moment.updateLocale('de',{
    monthsShort: ['Jan', 'Febr', 'Mrz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sept', 'Okt', 'Nov', 'Dez']
});

let dateStr = "07 Okt 2020";

let dt = moment(dateStr, "DD MMM YYYY", "de");
console.log("Date formatted as YYYY-MM-DD:", dt.format("YYYY-MM-DD"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment-with-locales.min.js" integrity="sha512-EATaemfsDRVs6gs1pHbvhc6+rKFGv8+w4Wnxk4LmkC0fzdVoyWb+Xtexfrszd1YuUMBEhucNuorkf8LpFBhj6w==" crossorigin="anonymous"></script>

Upvotes: 1

Related Questions