dannymcc
dannymcc

Reputation: 3814

Sorting records based on modified timestamp?

I am trying to sort a list of records that have been created using a screen scraping script. The script adds the following style of date and time (timestamp) to each record:

13 Jan 14:49

The script runs every 15 minutes, but if I set the sort order to 'time DESC' it doesn't really make sense because it lists the records as follows:

13 Jan 14:49
13 Jan 12:32
13 Jan 09:45
08 Feb 01:10
07 Feb 23:31
07 Feb 06:53
06 Feb 23:15

As you can see, it's listing the first figure correctly (the day of the month in number form) but it's putting February after January. To add to the confusion it's putting the latest date in February at the top of the February section.

Is there a better way of sorting these so they are in a more understandable order?

Upvotes: 1

Views: 402

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176472

If you are storing the values in a database, simply use the column type datetime when creating the field. The database will treat the field as time and will sort the values chronologically.

Otherwise, if you are storing the values elsewhere, for example in a flat file, convert the formatted time to unix time. Unix time is an integer, thus you can sort it easier.

Time.parse("13 Jan 09:45").to_i
# => 1326444300
Time.parse("08 Feb 01:10").to_i
# => 1328659800 

You can always convert a unix time to a Time instance.

Time.at(1328659800).to_s
# => "2012-02-08 01:10:00 +0100" 

Upvotes: 1

Related Questions