-1

I need to get always the same date string format for different user input string.

23.6.18
23.6.2018
23.06.18
23.06.2018

All these strings should result in DD.MM.YYYY

23.06.2018

Should I use momentJS for that? Right now I do not use that in my project. My problem is, that the input strings are string elements, not a real date value.

user3142695
  • 11,619
  • 29
  • 119
  • 238
  • possible duplicate [link](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – SirPilan Jun 23 '18 at 10:02
  • moment js is a good choice for a `date-picker`. You can also have a common method for DateToString parse to a JS `Date` object, just make sure you validate the user input before saving – omriman12 Jun 23 '18 at 10:04

2 Answers2

1

Resolve your string values, so the year part in 23.06.18 will always be returned as 2018 and not 18. Having proper data is always the best starting point in case you want your code to be as simple as possible.

Moving on, reverse your "date" value to ISO Date format, so Moment.js can understand. Like this:

const validDate = date.split('.').reverse().join('-');

Now, just pass validDate to moment(validDate).format('DD.MM.YYYY'); and it'll work.

Denialos
  • 887
  • 6
  • 14
0

You can simply do something like this with moment:

moment('23.06.18', 'DD.MM.YYYY').format('DD.MM.YYYY')

You may check the doc here: http://momentjs.com/docs/#/parsing/string-format/

VincenzoC
  • 24,850
  • 12
  • 71
  • 90
Swati Anand
  • 829
  • 4
  • 9