如何按日期升序对对象进行排序?
如果我有一个对象列表:
var objectList= LIST_OF_OBJECT;
列表中的每个对象包含三个属性:“名称”、“日期”、“性别”
如何按“日期”属性升序对列表中的对象进行排序?
(“日期”属性包含字符串值,例如“2002-08-29 21:15:31+0500”)
If I have a list of object:
var objectList= LIST_OF_OBJECT;
each object in the list contains three attributes: "name", "date","gender"
How to sort the objects in the list by "date" attribute ascending order?
(the "date" attribute contain string value like "2002-08-29 21:15:31+0500")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的对象在字符串字段中包含日期信息:
或者,如果它们在日期字段中包含该信息:
If your objects have the date information within a String field:
or, if they have it within a Date field:
Array.sort
方法接受排序函数,接受两个元素作为参数,并应返回:。
您很幸运,在您提供的日期格式中,另一个日期之前的日期也比使用字符串比较时的日期
<
。如果不是这种情况,您必须首先将字符串转换为日期:The
Array.sort
method accepts a sort function, which accepts two elements as arguments, and should return:.
You're lucky that, in the date format you've provided, a date that is before another date is also
<
than the date when using string comparisons. If this wasn't the case, you'd have to convert the string to a date first:您可以尝试:
You can try: