0

I am trying to sort date-time strings using Regex in my javascript code but am running into a problem. If the HH portion of the string "MM/DD/YYYY HH:MM:SS" is one digit, my program sorts that with a missing digit and is therefor a way smaller number and does not sort properly.

My regex is this (the part in question is in bold):

/^(\d{ 1,2 })[/- ](\d{ 1,2 })[/- ](\d{ 4 })[\s](\d{ 1, 2})[\:](\d{ 2 })[\:](\d{ 2 })[\s]([ AP]M)?/g

Is there a way to add a zero to the front of the HH if the number is one digit? And without using any .replace() methods, because that wont work in the section of my sort function.

Thanks in advance!

3 Answers3

0

You can't modify the string without using replace. You can "normalize" a date that matches your regex:

var out = old
.replace(/^(\d\d?)[\/ -](\d\d?)[\/ -](\d{4})\s(\d\d?):(\d\d):(\d\d)(?:\s([AP]M))?/g
,function(x,m,d,y,h,i,s,a) {
    if( m.length == 1) m = "0"+m;
    if( d.length == 1) d = "0"+d;
    if( a == "PM") h = ""+((h%12)+12);
    if( a == "AM" && h == 12) h = "0";
    if( h.length == 1) h = "0"+h;
    return y+m+d+h+i+s;
});

For today's date, this would return:

20121130141320

The date components are sorted from biggest to smallest, which means a simple .sort() call would arrange the dates in the right order with no fuss.

NOTE: I edited your regex a little, but it still matches the same stuff. The only difference is that now if there is no AM or PM, the space at the end is no longer required.

Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
0

Can you call a custom sort function that converts the strings into Date objects to compare them?

Similar to: Sort Javascript Object Array By Date

Community
  • 1
  • 1
Brandon
  • 983
  • 6
  • 15
0

I'm kind of late on the subject, but personnally, I don't feel like using regex on this. I do prefer keep things simplier when I can, hence the use of ternary operators :

// now (I'm posting at 03/05, so let's take this value)
var datev = new Date(); 

/* 
* here we will simply concatenate the value with a prefix "0" if the number
* is lower than 10. If not, concatenate the original value.
*/
var string_date = (datev.getMonth()+1 < 10 ? "0"+datev.getMonth()+1 : datev.getMonth()+1) + "/" + (datev.getDate() < 10 ? "0"+datev.getDate() : datev.getDate()); 

// display 03/05 instead of 3/5
console.log(string_date); 

Wanted to add this method to bring some variety on the topic.

Note : The getMonth() return a value between 0 and 11 so you have to add 1 to it in order to get the correct value.

Alex
  • 4,111
  • 3
  • 17
  • 36