如何在jQuery中比较两个日期格式为dd/mm/yyyy hh:mm:ss的日期 [英] How to compare two dates having format dd/mm/yyyy hh:mm:ss in jquery

查看:440
本文介绍了如何在jQuery中比较两个日期格式为dd/mm/yyyy hh:mm:ss的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个日期,格式为dd/mm/yyyy hh:mm:ss.当我使用<或>进行比较,我得到了错误的结果.我尝试了新的日期('dd/mm/yyyy hh:mm:ss'),然后对它们进行比较,但我仍然得到了错误的结果.

I have two dates with format dd/mm/yyyy hh:mm:ss. When i use < or > to compare ,i am getting wrong results.I have tried new date('dd/mm/yyyy hh:mm:ss') and comparing them still i am getting wrong results.

任何人都可以帮忙,谢谢.

Can any one help please, Thanks in advance.

推荐答案

最简单的方法是将它们转换为Date对象.但是,由于您使用的日期格式为dd/mm/yyyy,因此它实际上不会起作用. (默认情况下,Date使用ISO 8601格式-yyyy-mm-dd.因此,您需要将格式转换为javascript可以理解的格式.

The easiest way is to convert them to Date objects. However, since you're using a date with the dd/mm/yyyy format it won't really work. (By default Date uses the ISO 8601 format - yyyy-mm-dd. So you need to convert the format to something javascript can understand.

// convert to a parseable date string:
var dateStrA = "28/12/2013 16:20:22".replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
var dateStrB = "28/12/2013 16:20:11".replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");

// now you can compare them using:
new Date(dateStrA) > new Date(dateStrB);

有点混乱,但是可以解决问题.

A bit messy, but does the trick.

请注意,使用等号(例如===)进行比较将不适用于Date对象.您还可以使用Date.compare()或强制转换为数字,或在日期调用.getDate()

Beware that comparing using equals, such as === will not work on Date objects. You can also use Date.compare() or casting to numbers or call .getDate() on the date

这篇关于如何在jQuery中比较两个日期格式为dd/mm/yyyy hh:mm:ss的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆