11

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.

ClydeM
  • 295
  • 1
  • 3
  • 10
  • 1
    Can you elaborate on *how* it is getting "messed up"? The Moment.js API supports these formats. If you give it: `moment('4-1-2013', 'D-M-YYYY')` it will interpret that as January 4, 2013. – founddrama Feb 04 '13 at 11:52

4 Answers4

18

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.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
11

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
timrwood
  • 10,611
  • 5
  • 35
  • 42
2

If the date variable is in a String format(for example from input[type=date]) then you need to split the data component into single items.

date = date.split('-');

then check both the day's and the month's length

day = date[0].length==1 ? "0"+date[0] : date[0];
month = date[1].length==1 ? "0"+date[1] : date[1];

then get them back together into a format that you desire

date = ""+day+month+date[2];

Working example: http://jsfiddle.net/dzXPE/

Dharman
  • 30,962
  • 25
  • 85
  • 135
0
var day = new Date();
day = day.getDay();
if(day.toString().length <= 1) {
    day = '0' + day;
}

You can use the same for month. I'm not entirely sure you need to convert to string but it wouldn't hurt.

Martin
  • 461
  • 2
  • 9
  • 1
    It would work as the dates I get are strings. You cant define day.getDay(). Imagine 7-4-2013 is a word. – ClydeM Feb 04 '13 at 11:43