androidjava-calendar

How to set Calendar according to Timezone


I want to make a Calendar according to Timezone. I tried to resolve the issue by surfing different queries but i can't. Now it pick mobile default time. If anyone have idea please help me. Timezone should be UK time.

I tried:

{
    Calendar c1;
    c1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.UK);
    int hour = c1.get(Calendar.HOUR);
    int minutes = c1.get(Calendar.MINUTE);
    int seconds = c1.get(Calendar.SECOND);
    int day = c1.get(Calendar.DAY_OF_MONTH);
    int month = c1.get(Calendar.MONTH);
    int year = c1.get(Calendar.YEAR);
} 

But it also returns System date.


Solution

  • java.time

        ZonedDateTime nowInUk = ZonedDateTime.now(ZoneId.of("Europe/London"));
        int hour = nowInUk.getHour();
        int minutes = nowInUk.getMinute();
        int seconds = nowInUk.getSecond();
        int day = nowInUk.getDayOfMonth();
        Month month = nowInUk.getMonth();
        int year = nowInUk.getYear();
    
        System.out.println("hour = " + hour + ", minutes = " + minutes + ", seconds = " + seconds 
                + ", day = " + day + ", month = " + month + ", year = " + year);
    

    When I ran this snippet just now, it printed:

    hour = 3, minutes = 41, seconds = 15, day = 5, month = OCTOBER, year = 2018

    ZonedDateTime largely replaces the outdated Calendar class.

    What went wrong in your code?

    Time zone ID for UK time is Europe/London. In your code you used UTC, which is something else and wll give you a different result, at least sometimes. UK time coincides with UTC some of the year in some years, but not at this time of year this year. So you got a time that was one hour earlier than UK time.

    Also c1.get(Calendar.HOUR) gives you the hour within AM or PM from 1 through 12, which I don’t think was what you intended.

    Question: Can I use java.time on Android?

    Yes, java.time works nicely on Android devices. It just requires at least Java 6.

    Links