Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Date: Add 0 in front of every single day or month

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.

like image 236
ClydeM Avatar asked Feb 04 '13 11:02

ClydeM


2 Answers

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.

like image 85
Alnitak Avatar answered Nov 08 '22 03:11

Alnitak


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
like image 43
timrwood Avatar answered Nov 08 '22 03:11

timrwood