Recently i've tried to use milliseconds representation of current date as a primary key for a database (Realm).
I could get date as a string and store it, but since i needed to perform fast ascending search on big amount of data i decided to store data in milliseconds format.
To achieve this i followed these steps:
1) Initialize a GregorianCalendar instance and pass current date
Calendar c = new GregorianCalendar();
c.setTime(new Date());
2) Set time to match exactly a midnight of current day
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
3) Convert results to milliseconds
c.getTime().getTime()
Later i tested it by inserting objects to database. Below is the log output. I calculated the same date several times, all by code above without any changes.
01-03 06:59:38.607 16256-16256/com.example.bizarre.bindaccess D/Day: Long: 1 422 528 534 032 Date: 29.01.15
01-03 06:59:38.611 16256-16256/com.example.bizarre.bindaccess D/Day: Long: 1 422 528 647 420 Date: 29.01.15
01-03 06:59:38.611 16256-16256/com.example.bizarre.bindaccess D/Day: Long: 1 422 528 669 794 Date: 29.01.15
01-03 06:59:38.611 16256-16256/com.example.bizarre.bindaccess D/Day: Long: 1 422 528 707 566 Date: 29.01.15
01-03 06:59:38.615 16256-16256/com.example.bizarre.bindaccess D/Day: Long: 1 422 532 686 557 Date: 29.01.15
01-03 06:59:38.615 16256-16256/com.example.bizarre.bindaccess D/Day: Long: 1 422 532 726 052 Date: 29.01.15
01-03 06:59:38.615 16256-16256/com.example.bizarre.bindaccess D/Day: Long: 1 422 532 754 147 Date: 29.01.15
Despite of my actions to zero hours, mins, secs and millis and by that get a cleared midnight value in millis everytime i get slightly different value.
My suggestions are:
1) It depends on device time scheme.
2) It has something to do with android by itself.
3) A trouble is on my side.
Would be really glad if someone could help me out.
P.S. I also used a site http://www.fileformat.info/tip/java/date2millis.htm to get millis of 29.01.15, result was 1 422 489 600 000.
Updated #1. 1) All inserts were on the same device, local timezone was not changed, so environment was not affected anyhow. 2) As i have stated above, maybe it wasn't clear - i save data in millis, in a class field of type long. That field is also not affected anyhow.
Updated #2. Actually, my question was: "How could behaviour i encountered be explained?". But since it might be too broad or unclear, i focus this on what i initially wanted to achieve - "How to get the current date in local (on-device) time zone in a form of consistent milliseconds value (type of long)?"