Android Joda DateTime one hour off - android

I have a TimePickerDialog which lets the user pick a time. The TimePickerDialog has a onTimeSet method that gets called when the user finished picking the time.
I pass the arguments to a second method, setTime(int hour, int minute) which saves the values and displays a formatted time.
Here is a code snippet of the method:
java.text.DateFormat dateFormatter =
java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT, Locale.getDefault());
DateTime dt = new DateTime();
dt = dt.hourOfDay().setCopy(hour);
dt = dt.minuteOfHour().setCopy(minute);
String text = dateFormatter.format(dt.toDate());
The Problem is that (sometimes, not always) the hour value is off by one or maybe even two hours. I think the cause of the problem has something to do with timezones, but I do not know what the exact cause is. I also think that the problem is caused by the Joda DateTime object, since I did not have any issues before I implemented Joda time AND because it also gets saved with one hour off.
Any ideas what happens / how to fix it?

For this answer, I'm using joda-time 2.7 (although it might work with previous versions).
I'm also assuming that your program only cares about hour and minute (I'm not an Android expert, but I saw docs from TimePickerDialog and it seems to be the case).
So, if you're manipulating only hour and minute, you don't need to use DateTime class (actually you shouldn't in this case).
That's because a DateTime object is "aware" of all date fields, including day, month, year and timezone. So, when you create a new DateTime(), it creates a new object with current date and time in your default timezone. And if the current date in default timezone is in summer time (aka daylight saving time), you can have these hour shifts.
(And I believe that Android takes the default timezone from the device's system, so it can vary according to the device running the code - at least that's how it works in computers, so it shouldn't be different for devices).
As you don't need to know day/month/year and timezone, you can use LocalTime class (org.joda.time.LocalTime) which is a class with only hour and minute fields (and seconds, if you want; if you don't care about seconds, they'll be set to zero). And the best part is: this class doesn't care about timezones, so 10:00 AM will always be 10:00 AM.
You also don't need to use java.text.DateFormat, as joda-time has its own formatters. So the code will be like this:
public void setTime(int hour, int minute) {
// shortTime() is equivalent to DateFormat.SHORT
DateTimeFormatter fmt = DateTimeFormat.shortTime().withLocale(Locale.getDefault());
LocalTime time = new LocalTime(hour, minute);
String text = fmt.print(time);
System.out.println(text);
}
Doing some tests (assuming default locale is en_US):
setTime(9, 30); // prints 9:30 AM
setTime(10, 0); // prints 10:00 AM
PS: the output may vary according to your default Locale (which I also believe it comes from the device's system). If you want a fixed format (independent from locales), you can use DateTimeFormat.forPattern("h:mm a"), which also results in the output above (and when you use formatters this way, the default locale doesn't change the output).

Related

Difference between 2 dates in days and in double

I am working on an app and i need to get the difference between the actual date and a date inserted by the user, in days and in double.
Any idea on how to make this? I've tried some things but without success.
First you must decide if you want to consider the time of the day and the timezone to calculate the difference, because this can lead to different results.
Example: current date (AKA "today") is April 17th or 18th, depending on where in the world you are. Actually, depending on the time of the day, there might be 3 different "todays" in the world, at the same time. What timezone are you using to calculate the difference?
the user will enter a date: only day, month and year? Will it enter the hours? Are you using the user's device's timezone or some specific zone?
the same questions apply to the current date
Depending on the choices you make, you might get a different result.
Anyway, I'd use this lib: http://www.threeten.org/threetenbp/
or java.time classes, if available in your API level. In both API's you can use the following.
To use a date (day-month-year only) and the device's default timezone, I'd choose the LocalDate class:
// current date in device's default timezone
LocalDate now = LocalDate.now();
// some date from input values (May 10th 2018)
LocalDate dt = LocalDate.of(2018, 5, 10);
// difference in days
long diff = ChronoUnit.DAYS.between(now, dt); // 23
If you want to consider the time of the day (hours, minutes, etc), use a LocalDateTime. But in this case, ChronoUnit.DAYS considers a day has passed when the time is >= the other (ex: the difference between April 17th at 10 AM and April 18th 9:59 AM is zero days, because the time of the day didn't reach 10 AM, so it didn't complete 1 day - with LocalDate this doesn't happen because this class doesn't have time-of-the-day fields and considers only the day, month and year).
If you want to consider everything (date, time, and timezone), including Daylight Saving Time transitions, use a ZonedDateTime instead (the code is very similar, the only difference is that you can choose a timezone to work with):
// current date/time in device's default timezone
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
// some date from input values (May 10th 2018, 10 AM in New York timezone)
ZonedDateTime dt = ZonedDateTime.of(2018, 5, 10, 10, 0, 0, 0, ZoneId.of("America/New_York"));
// difference in days
long diff = ChronoUnit.DAYS.between(now, dt); // 23
You can choose between the device's default timezone (ZoneId.systemDefault()) or a specific one (ZoneId.of("America/New_York")). You can check all the available timezones with ZoneId.getAvailableZoneIds().
Maybe it doesn't make sense to use current date in one timezone and user's date in another (I'd use the same for both), but that's up to you to decide.
Calendar c = Calendar.getInstance();
Calendar c2 // = what you will get from the user
long diff = c.getTimeInMillis()-c2.
double days = (double) diff/(1000*60*60*24);
that is what i have in mind.
I hope this helps
use this way
public static double getTimeDiffBetweenDate(Date startDateTime, Date finishDateTime) {
long diffInMilliseconds = finishDateTime.getTime() - startDateTime.getTime();
return TimeUnit.MILLISECONDS.toMinutes(diffInMilliseconds) / 60.0;
}

getting local time on Android

I tried:
TimeZone.getDefault();
I tried:
Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
I tried:
Calendar c = Calendar.getInstance();
mTimeZone = c.getTimeZone();
No matter what I try... it gives me a default of 0 and GMT. My app just cannot seem to get the time zone (it should read -4 or ET, i.e. eastern USA time zones)
The strange thing is... my clock displays the correct time on my phone.
the "use automatic time zone" is checked in settings of my android device.
So why can't I get the local time in my app? how does the Android clock able to achieve this but not me?
I have checked online and cant seem to find anything. Is there at least a way to sync with the clock app and receive it's time to display on my app as well? Is there ANY way to get the correct time on my app?
System.getMilliseconds() return the time since epoch, which would only function as the current time in areas that use GMT. (As long as what you are using doesn't make it's own conversion)
To get local time in milliseconds since epoch, you can use this function:
// Kotlin
fun getLocalTime(): Long
{
val currentDate = Calendar.getInstance()
return currentDate.timeInMillis + TimeZone.getDefault().getOffset(currentDate.timeInMillis)
}
Which in Java would probably look like this:
// Java
static long getLocalTime()
{
Calendar currentDate = Calendar.getInstance();
return currentDate.getTimeInMillis() + TimeZone.getDefault().getOffset(currentDate.getTimeInMillis());
}
The function takes the time since epoch and adds to it the timezone offset of the phone's local timezone.

Change Joda DateTime timezone but don't change time

I am using (maybe incorrectly) a Joda DateTime to store a reminder time in a reminders app. When the timezone changes on the device (because of DST or just moving to a different TZ) I want to be able to reset the reminders to use the current timezone but keep the time.
For example: I set a reminder for Friday May 15th, at 15:00. If the timezone changes before that time, I want to be able to recreate the reminder for Friday May 15th at 15:00 local time.
I have already tried to use withZoneRetainFields but I haven't been able to keep the time unchanged:
new DateTime(reminderTimeMillis, DateTimeZone.forID(previousTimeZone)).withZoneRetainFields(DateTimeZone.getDefault())
Well, that method should basically work:
#Test
public void change_timezone_of_reminder() {
DateTime originalReminderDateTime = LocalDateTime.parse("2015-05-15T15:00").toDateTime(
DateTimeZone.forID("Europe/Berlin"));
assertThat(originalReminderDateTime.toString(), equalTo("2015-05-15T15:00:00.000+02:00"));
long reminderMillis = originalReminderDateTime.getMillis();
DateTime updatedTime = new DateTime(reminderMillis, DateTimeZone.forID("Europe/Berlin"))
.withZoneRetainFields(DateTimeZone.forID("America/New_York"));
assertThat(updatedTime.toLocalDateTime(), equalTo(LocalDateTime.parse("2015-05-15T15:00")));
assertThat(updatedTime.toString(), equalTo("2015-05-15T15:00:00.000-04:00"));
}
So, how are you evaluating that the time field is not changing?
Also, if you are storing the reminder time as millis-after-epoch, you don't need to adjust it for DST shifts, if you're calculating the millis using a full timezone ("Europe/Berlin") rather than a fixed offset.

Android inconsistency when dates are stored as longs and the time zone is changed

I have an Android app that is used by people in the UK and Ireland only, and there are no plans for this app to be used overseas.
In the app I store dates for various things, although I never need the full timestamp including the time of day, I only need the date.
So that I can compare dates easily, I've been creating calendar objects and clearing the values of the time, and using the milliseconds of that to store in the database.
public Calendar clearCalTime(long l) {
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setTimeInMillis(l);
cal.clear(Calendar.HOUR);
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
return cal;
}
The issue has been that if users change the timezone, for some reason the dates start messing up, e.g by saving things to the wrong day. The timezones could be anything, I have no control over what the users set.
I've tried setting the timezone to UTC but this doesn't work either. Is there any way to just disregard the timezones?
Nope. You are going to have to set TimeZone going in and out of your storage.
You'll need to do this:
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
in your code to make it consistent.
See this SO: Java.util.Calendar - milliseconds since Jan 1, 1970
Alternatively use Joda Time when dealing with complicated Date/Time math.

Android: getting the time

i am currently using the following line to achieve the time: System.currentTimeInMilis.
I have noticed it doesn't consider time zones,or does it not match the android phone it self by the time, while on the emulator it does match.s
so is there another type of way to get the android clock it self? so when the user adjusts he's phones built in clock, it affects it too?
float getTime()
{
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(System.currentTimeMillis());
cal.setTimeZone(TimeZone.getDefault());
return cal.getTimeInMillis();
}
Read the documentation of currentTimeMillis. It has a time zone, which happens to be UTC (which is the default for Unix time stamps).
If you want to convert it to a different time zone you can make use of the Java Calendar and TimeZone classes:
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(System.currentTimeMillis());
cal.setTimeZone(TimeZone.getDefault());
Alternatively you can just create a new GregorianCalendar instance. By default its TimeZone will match the local one (as set on the device) and the time will be set to "now".
There are also other ways for retrieving the current time according the current time zone and locale as string. Take a look at DateUtils.
EDIT Explaining the usage of Calendar
Read the documentation for Calendar.getTimeMillis(). That method returns the Unix time stamp again which happens to have the time zone UTC.
You have to use the Calendar.get() method instead for getting the correct values. See following example for getting the current hour in the correct time zone via your calendar object:
int hour = cal.get(Calendar.HOUR_OF_HAY);
Read the documentation of Calendar. There are plenty of fields like HOUR_OF_DAY which help you getting values like the year, month, minute, seconds etc.

Categories

Resources