How to compare two times in java?

青春壹個敷衍的年華 提交于 2019-12-08 14:09:02

问题


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 to convert this string to time? and

2.How to compare the two times?

2014-07-11 15:10:55 this is my time format.

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


回答1:


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

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.)

As for comparing values:

  • 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

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




回答2:


I suggest you to store timestamps in the sqlite database.

getTime() and setTime(long) could help you convert between Date object and a timestamp.

Moreover, you could also compare timestamps directly as a long integer. They are the number of milliseconds since January 1, 1970, 00:00:00 GMT.




回答3:


Another possibility is to store the miliseconds in the datebase as int. By using the getTimeInMillis() seconds you can get the time in miliseconds whics is easy to store in your database. Comparing would be easy like this:

if(time1> time2)



来源:https://stackoverflow.com/questions/24726584/how-to-compare-two-times-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!