Hienz
Hienz

Reputation: 718

MomentJS convert localized date to UTC

I'm currently having the following date string in german format:

01.09.2021, 14:28:53 // which means the 1st of September, 2021

and I try to parse it to UTC, but unfortunatelly when I do it, it switches days with months.

2021-01-09T14:28:53.000Z

The code that I have:

const date: string = '01.09.2021, 14:28:53';
moment.utc(date).locale('de').toISOString();

What I try to achieve is:

2021-09-01T14:28:53.000Z

Upvotes: 0

Views: 32

Answers (2)

mplungjan
mplungjan

Reputation: 177692

No need for moment

const de = true; // as opposed to en = true;
const str = `01.09.2021, 14:28:53`
const [_,aa,bb,yyyy,t] = str.split(/(\d{2})\.(\d{2})\.(\d{4}), (\d{2}\:\d{2}\:\d{2})/)
dd = de ? aa : bb;
mm = de ? bb : aa;
console.log(dd,mm,yyyy,t);
console.log(`${yyyy}-${mm}-${dd}T${t}.000Z`);

Upvotes: 0

0stone0
0stone0

Reputation: 43904

Pass your custom format

const date = '01.09.2021, 14:28:53';
const tmp = moment(date, 'DD.MM.YYYY, HH:mm:ss').locale('de').toISOString();
console.log(tmp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Upvotes: 2

Related Questions