开发者

How can I sort dates in Perl?

开发者 https://www.devze.com 2022-12-23 22:50 出处:网络
How can I sort the dates in Perl? my @dates =( \"02/11/2009\" , \"20/12/2001\" , \"21/11/2010\" ); I have above dates in my array . How can I s开发者_StackOverflow社区ort those dates?

How can I sort the dates in Perl?

my @dates =  ( "02/11/2009" , "20/12/2001" , "21/11/2010" ); 

I have above dates in my array . How can I s开发者_StackOverflow社区ort those dates?

My date format is dd/mm/YYYY.


@dates = sort { join('', (split '/', $a)[2,1,0]) cmp join('', (split '/', $b)[2,1,0]) } @dates;

or using separate sorting subroutine:

sub mysort {
    join('', (split '/', $a)[2,1,0]) cmp join('', (split '/', $b)[2,1,0]);
}
@dates = sort mysort @dates;

Update: A more efficient approach is the Schwartzian Transform:

@dates = 
    map $_->[0],
    sort { $a->[1] cmp $b->[1] }
    map  [ $_, join('', (split '/', $_)[2,1,0]) ], @dates;


I prefer the YYYY/MM/DD format better, for just this reason. It's guaranteed to sort dates properly, between 1000/01/01 and 9999/12/31.

my @sorted_alt = sort map { join '/', reverse split '/', $_  } @dates;

If you really need it in DD/MM/YYYY format, you could always go for a complete Schwartzian transform.

my @sorted = map {
  join '/', reverse split '/', $_
}
sort
map {
  join '/', reverse split '/', $_ 
} @dates;

or

my @sorted = map {
  join '/', reverse @$_
}
sort { "@$a" cmp "@$b" }
map {
  [ reverse split '/', $_ ]
} @dates;


Or use the epoch format in timestamp and sort them as numbers. Then convert date strings output as you want. Then you are not stuck with formatting the origin strings.


Many people here argued correctly that the original format of the dates should be in yyyy-mm-dd format, but nobody has given the Perl code that can handle that case yet. So here it is:

my @dates = (
    '2014-08-15',
    '2016-09-13',
    '2001-01-02',
    '1998-09-22',
    '1998-09-21',
    '1998-09-23',
    '1999-04-20',
    '2020-01-30',
);

@dates = sort {$a cmp $b} @dates;   # 1998 is the first date's year
@dates = sort {$b cmp $a} @dates;   # 2014 is the first date's year
0

精彩评论

暂无评论...
验证码 换一张
取 消