0

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?

curious
  • 1,504
  • 5
  • 18
  • 32
Sander Mez
  • 67
  • 1
  • 8

1 Answers1

0

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.

Nimrod Rappaport
  • 134
  • 1
  • 1
  • 12