ThreeTenABP
My suggestion is you skip the outdated classes Calendar
and GregorianCalendar
and start using the modern Java date and time API. It’s much nicer to work with. Even when DatePicker
return values are designed for use with the old classes. And even when the modern API isn’t native on very many Android phones yet (that will come).
You will need to get the ThreeTenABP library. Useful question: How to use ThreeTenABP in Android Project. Then your code could go like this:
long dps = LocalDate.of(dpStart.getYear(), Month.values()[dpStart.getMonth()],
dpStart.getDayOfMonth())
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
String newStartDate = Long.toString(dps);
Picking 4 September 2017, the result will be 1504483200000
.
My way of converting from the date picker’s 0-based month to LocalDate
’s more human 1-based month is a bit peculiar. If you find it simpler just to add 1, that will work too:
long dps = LocalDate.of(dpStart.getYear(), dpStart.getMonth() + 1, dpStart.getDayOfMonth())
// …
I have renamed your variables to conform with Java coding conventions. They say a variable name should begin with a lowercase letter.
As an aside, I believe that accepted best practices for storing timestamps is you store either the Instant
you get from toInstant()
or its string representation (from toString()
) rather than the millisecond value. Millisecond values are very hard for most of us to interpret, for example when we see them in the debugger. Instant
values are readily understood, at least roughly what time they refer to. An even better human-readable format would be the string representation of the LocalDate
, it looks like 2017-09-04
. The string representations of both Instant
and LocalDate
conform with ISO 8601.
The outdated solution
If you definitely don’t want to rely in a third party library like ThreeTenABP, even temporarily until the modern date and time API comes to Android, I believe the solution with Calendar
is (1) make sure it uses UTC time zone (2) clear the hours, minutes, seconds and milliseconds to make sure you get the time at midnight:
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
calendar.clear();
calendar.set(dpStart.getYear(), dpStart.getMonth(), dpStart.getDayOfMonth());
The result is the same as above.