0

I'm storing time in my database by setting year, month, day, hour, and minute individually, and I would like to know the date difference between two datetimes. This is clumsy and cumbersome, and I would like to know what the best practice for doing something like this:

1/1/2016 12:00am - TimeUnit.MINUTES.toMillis(1800000) = 12/31/2015 11:30pm
405 Freeway
  • 518
  • 5
  • 12

2 Answers2

2

I had to do something similar and came to realize that Java's Date class is shit. Luckily someone really kind out there made an amazing library called JodaTime. Here is the android version: https://github.com/dlew/joda-time-android

With JodaTime you can do something like this:

date.minusMinutes(1);//this subtracts a minute from your date time variable
date.plusHours(3);//adds 3 hours
date.before(anotherDate);//checks if date is earlier in time than anotherDate
Sree
  • 2,727
  • 3
  • 29
  • 47
  • FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advising migration to the [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jun 20 '19 at 20:35
1

I prefer to store dates as a single column containing the time in milliseconds, e.g. the same thing you would get by calling System.currentTimeMillis(). It's easy to convert this back to a date using the Calendar class. You could also subtract the 1800000 from it first and then convert to a date with Calendar.

Karakuri
  • 38,365
  • 12
  • 84
  • 104
  • Using a count-from-epoch is error-prone as humans cannot discern the meaning of the data. Much harder to detect bugs and monitor your data. Better to use a proper date-time type in your database. The SQL standard does define some date-time types. A moment, a specific point on the timeline, should be stored in a column of type `TIMESTAMP WITH TIME ZONE`. – Basil Bourque Jun 20 '19 at 20:36