I have this date parsed from an api as a string: DD-MM-YYYY but sometimes the date is DD-M-YYYY or even D-M-YYYY.
For example:
4-1-2013 or 10-10-2013 or 7-4-2013
The year is always 4 digits but days or months sometimes get one digit. How can I manually (with JS) add 0 in front of a every single digit ?
I am using moment.js for some calculations thus I am remove the '-' using
date.replace("-", "")
to get a whole number (eg. 4-1-2013 = 412013) so I can use it with moment.js but if its a single digit, it all gets messed up.
You can normalise your strings first like this:
date = date.replace(/\b(\d{1})\b/g, '0$1');
which will take any "word" that is just a single digit and prepend a zero.
Note that to globally replace every -
you must use the regexp version of .replace
- the string version you've used only replaces the first occurrence, therefore:
date = date.replace(/\b(\d{1})\b/g, '0$1').replace(/-/g, '');
will do everything you require.
Moment.js supports formats with dashes, so you don't even need to do any string handling.
moment('4-1-2013', 'MM-DD-YYYY').format("MMDDYYYY"); // 04012013
moment('10-10-2013', 'MM-DD-YYYY').format("MMDDYYYY"); // 10102013
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With