如何在Java中比较两个时间? [英] How to compare two times in java?

查看:428
本文介绍了如何在Java中比较两个时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发同步联系人应用程序。
每个联系人有UPDATE_TIME场。
我想的比较当前UPDATE_TIME previous UPDATE_TIME

I am developing a app for sync contacts. Every contact have a update_time field. I want to compare this current update_time to previous update_time.

我的问题是我这个存储的时间字符串格式在我的数据库

My problem is I am storing this time as string format in my database.

1.How这个字符串转换为时间?

2.How到两次比较?

2014年7月11日15点十分55秒这是我的时间格式。

任何帮助或意见,欢迎。感谢您的宝贵答案。

any help or comments welcome. thank you for your valuable answers.

推荐答案

(您可能需要的认为的存储在数据库中的值作为整数,而不是为文本。有优点和缺点在这里,所以我就离开,作为一个想法是有点不同的,以你的实际问题。)

(You may want to consider storing the values in your database as integers instead of as text. There are pros and cons here, so I'll just leave that as a thought which is somewhat separate to your actual question.)

解析是相当容易,如果你很高兴解析为 java.util.Date

The parsing is reasonably easy, if you're happy to parse into a java.util.Date:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

指定在美国地区停止从设备的默认语言环境的影响什么。 (由于这些都只是数字,这是不太可能无论如何 - 但它只是可以想象,它可以使用不同的日历系统)

Specifying the US locale stops anything from being influenced by your device's default locale. (As these are just numbers, it's less likely anyway - but it's just conceivable that it could use a different calendar system.)

至于比较的值:


  • 如果您是在文本形式比较两个值,你可以只用 String.compareTo ;的ISO-8601格式的好处之一是,它的排序。如果你比较这是在数据库中的值,你可以做,在以同样的方式SQL查询,再次因为ISO-8601的定义方式。

  • 否则,请日期形式这两个值,并比较这些与 Date.compareTo

  • If you're comparing two values in text form, you can just use String.compareTo; one of the benefits of the ISO-8601 format is that it's sortable. If you're comparing values which are in the database, you can do that in the SQL query in the same way, again because of the way that ISO-8601 is defined.
  • Otherwise, get both values in Date form, and compare those with Date.compareTo

请注意,如果你可以使用约达时间,这比<$普遍更好的日期/时间API C $ C> java.util.Date 等。

Note that if you can use Joda Time, that's a generally nicer date/time API than java.util.Date etc.

这篇关于如何在Java中比较两个时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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