custom sorting with heavely formated date

custom sorting with heavely formated date

ty105ty105 Posts: 15Questions: 5Answers: 0

Hi!

I have a formatted date column that i want to be able to sort by in my table. i have tried to figure it out but i cannot, if someone could help me or send me in the right direction, i would love it.

an example of how it looks is this;

just now
2 hours ago
5 hours ago
5 hours ago
yesterday
yesterday
2 days ago
6 days ago
3 weeks ago
3 weeks ago 
3 weeks ago
last month
last month
april 2015
march 2015
march 2015
february 2015

here is the code that creates this format

function time2str($ts)
{
    if(!ctype_digit($ts))
        $ts = strtotime($ts);

    $diff = time() - $ts;
    if($diff == 0)
        return 'now';
    elseif($diff > 0)
    {
        $day_diff = floor($diff / 86400);
        if($day_diff == 0)
        {
            if($diff < 60) return 'just now';
            if($diff < 120) return '1 minute ago';
            if($diff < 3600) return floor($diff / 60) . ' minutes ago';
            if($diff < 7200) return '1 hour ago';
            if($diff < 86400) return floor($diff / 3600) . ' hours ago';
        }
        if($day_diff == 1) return 'Yesterday';
        if($day_diff < 7) return $day_diff . ' days ago';
        if($day_diff < 31) return ceil($day_diff / 7) . ' weeks ago';
        if($day_diff < 60) return 'last month';
        return date('F Y', $ts);
    }
}

I really hope someone can help me with this. thank you guys and have a great day!!
-ty105

This question has an accepted answers - jump to answer

Answers

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395

    Use a hidden column containing your actual "$ts" values, and sort on that.

  • ty105ty105 Posts: 15Questions: 5Answers: 0
    edited August 2015

    that is a great idea!! thank you.
    how would i get the column to sort off of the hidden column?
    sorry, i am new to this whole platform.

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395
    Answer ✓

    To hide a column:

    http://datatables.net/examples/basic_init/hidden_columns.html

    Then in your "columnDefs":

        { 
        // Sort column 1 (formatted date) by column 6 (hidden seconds)
        "orderData":[ 6 ],   "targets": [ 1 ] 
        }, 
    

    Column numbering is entirely up to you of course.

  • ty105ty105 Posts: 15Questions: 5Answers: 0

    thank you so much tangerine!

This discussion has been closed.