Best way to store, retrieve, and compare dates in Java

android, date, java, sqlite, time

Solution

Just use a primitive long. The same one returned from `System.currentTimeMillis();` (for the current time). It is the number of milliseconds since 1970. It is basically the same as unix time but with a signed 64bit value (java long) and in milliseconds instead of seconds.

A `java.util.Date` object is just a wrapper around a `long` too, so mostly pointless but easy to use with the Date object if you like too. Not to be confused with `java.sql.Date`

You can then compare times just as in your example

long time1 = System.currentTimeMillis();
long time2 = ...;

if (time2 < time1) {

Problem

I come from a PHP background. I've been a PHP developer for a long time now. I am wanting to jump into Android App development. I created one app, but I don't feel like I have a strong grasp of the time and date functions, especially when being stored in the database. O one of my main concerns is how to store and retrieve dates from the database (SQLite) and compare them. The way I do it in PHP is I simple; I use the `time()` function, which creates a unix timestamp for the current time, and then I store it as an integer in a MySQL database. This makes things very simple and easy due to MySQL's date functions, as well as the ability to easily retrieve and compare the date via PHP as an integer. So basically, I'm wondering what the best solution would be for Java. What do you recommend I do when creating, storing, retrieving, and comparing dates for my future Android apps? Here is an example of the PHP code I'd use, perhaps this will give someone a better idea of what I'm used to and what I'm looking for: ``` Database structure: `id` (int) auto increment `username` (varchar) `the_date` (int) <?php $username = 'scarhand77'; $the_date = time(); // insert into database mysql_query("insert into `stack_overflow` (`username`, `the_date`) values ('$username', '$the_date')"); // retrieve from database $user_date = mysql_result(mysql_query("select `the_date` from `stack_overflow` where `username`='$username'"), 0); // compare $user_date, see if its older than right now if ($user_date < time()) echo 'it is older'; else echo 'it is not older'; ?> ``` Any help would be greatly appreciated.

Original source