markzzz
markzzz

Reputation: 47995

How can I order datetime strings in Javascript?

I get from youtube JSON request (after a small parsing of the objects) these strings (which should represents datetime) :

2009-12-16T15:51:57.000Z
2010-11-04T10:01:15.000Z
2010-11-04T14:00:04.000Z
2010-11-04T11:12:36.000Z
2010-11-04T10:24:26.000Z
2010-11-04T12:05:58.000Z
2010-04-30T13:28:08.000Z
2010-11-17T13:57:27.000Z

In fact I need to order these list (descending), for taking the recent video published. But how can I order those datetime? Is there a native method on JS?

Upvotes: 2

Views: 1250

Answers (3)

Bas Slagter
Bas Slagter

Reputation: 9929

You can just use a default sort method for this because the dates are perfectly formatted to do some sorting (year, month, day, hour, minute, second). This would be much more difficult if that was the other way around. Check out sort for example:

var unsortedArray = [ 
    "2009-12-16T15:51:57.000Z", 
    "2010-11-04T10:01:15.000Z", 
    "2010-11-04T14:00:04.000Z",
    "2010-11-04T11:12:36.000Z" ]; 

var sortedArray = unsortedArray.sort(); 

If you would like to reverse (descending) sorting, add .reverse() to the sorted array.

Upvotes: 2

Ray Toal
Ray Toal

Reputation: 88428

You asked for a descending sort. A quick way is to use reverse.

http://jsfiddle.net/6pLHP/

a = [
    "2009-12-16T15:51:57.000Z",
    "2010-11-04T10:01:15.000Z",
    "2010-11-04T14:00:04.000Z",
    "2010-11-04T11:12:36.000Z",
    "2010-11-04T10:24:26.000Z",
    "2010-11-04T12:05:58.000Z",
    "2010-04-30T13:28:08.000Z",
    "2010-11-17T13:57:27.000Z"
];
alert(JSON.stringify(a.sort().reverse()));

Upvotes: 1

Dominic Goulet
Dominic Goulet

Reputation: 8113

An easy way to achieve this would be to put all those into an array of strings and sort that array.

var arr = [ "2", "1", "3" ];
arr.sort(); // this gives [ "1", "2", "3" ]

You can read the full doc there :

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/sort

Upvotes: 2

Related Questions