-1

I am trying to sort a table of dates, yet the problem that I seem to have is that these dates are strings formatted as d M Y (so something like "04 SEPT 2016").

I'm assuming that these dates are not stored as timestamps in the database (if that makes sense), but rather as a normal string that needs to be converted back into something that can be sorted.

James K
  • 3,692
  • 1
  • 28
  • 36
benniy
  • 99
  • 7
  • you can use like this format: $current_date_time=$date->format( 'Y-m-d G:i:s' );... If you give clear information.. i could help you to solve you.. – Prajwal K M Sep 29 '16 at 12:07

4 Answers4

1

In PHP you can use the datetime interface. See specifics about the format specifier on the manpage. It allows to parse a date into an object by giving format specifiers. The DateTime class supports sorting and operators such as <, >, ==, etc.

You can parse a date using:

$list = [];
$d = DateTime::createFromFormat($time, 'd M Y');
$list[] = $d;  ### add to list

Now you can sort it as DateTime supports sorting:

sort($list);
reset($list);
foreach($list as $sorted_date) {
  ...
}

See also 2

Community
  • 1
  • 1
somnium
  • 1,487
  • 9
  • 15
1

It does make sense, and how you approach this will depend on what you want to do.

You can convert a string into a date using php's datetime function: (procedural method)

<?php
$date = date_create_from_format('j-M-Y', '15-Feb-2009');
echo date_format($date, 'Y-m-d');
?>

http://php.net/manual/en/datetime.createfromformat.php


Or, if you want to select/update/modify/etc within a MySQL database query (slight assumption that you'll be using MySQL), you can use the STR_TO_DATE function

STR_TO_DATE('21,5,2013','%d,%m,%Y');

http://www.mysqltutorial.org/mysql-str_to_date/

The bigger question here is whether you have scope to convert the dates from strings to dates within the DB, as this is the correct way to do things.

Chris J
  • 1,441
  • 9
  • 19
0

SELECT STR_TO_DATE(field, '%m/%d/%Y') FROM table ORDER BY STR_TO_DATE(field, '%m/%d/%Y')

0

If you want sort with PHP then you can try this trick:

<?php
    $myarray=array(
        "2 SEPT 2016",
        "9 SEPT 2016",
        "1 OCT 2016",
        "3 DEC 2016",
        "4 SEPT 2016",
    );
    usort($myarray, "cmpare");
    print_r($myarray);

    function cmpare($x, $y){ 
        return strcmp(strtotime($y), strtotime($x)); 
    }
?>
AHJeebon
  • 1,218
  • 1
  • 12
  • 17