2

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?

1
  • 1
    If the strings are in an array, just sort them descending. The beauty of ISO8601-formatted dates is that plain text sorting works! Commented Sep 6, 2011 at 8:30

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.