Get current time in a given timezone : android

后端 未结 10 1956
悲哀的现实
悲哀的现实 2020-11-30 10:13

I am new to Android and I am currently facing an issue to get current time given the timezone.

I get timezone in the format \"GMT-7\" i.e. string. and I have the sys

相关标签:
10条回答
  • 2020-11-30 10:25

    java.time

    Both the older date-time classes bundled with Java and the third-party Joda-Time library have been supplanted by the java.time framework built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date. See Oracle Tutorial. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

    By the way, never refer to an offset-from-UTC with a single digit of hours such as -7, as that is non-standard and will be incompatible with various protocols and libraries. Always pad with a zero for second digit, such as -07.

    If all you have is an offset rather than a time zone, use the OffsetDateTime class.

    ZoneOffset offset = ZoneOffset.ofHours( -7 );
    OffsetDateTime odt = OffsetDateTime.now( offset );
    String output1 = odt.toLocalTime().toString();
    System.out.println( "Current time in " + offset + ": " + output1 );
    

    Current time in -07:00: 19:41:36.525

    If you have a full time zone, which is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST), rather than a mere offset-from-UTC, use the ZonedDateTime class.

    ZoneId denverTimeZone = ZoneId.of( "America/Denver" );
    ZonedDateTime zdt = ZonedDateTime.now( denverTimeZone );
    String output2 = zdt.toLocalTime().toString();
    System.out.println( "Current time in " + denverTimeZone + ": " + output2 );
    

    Current time in America/Denver: 20:41:36.560

    See this code in action in Ideone.com.

    Joda-Time

    You can use Joda-Time 2.7 in Android. Makes date-time work much easier.

    DateTimeZone zone = DateTimeZone.forID ( "America/Denver" );
    DateTime dateTime = new DateTime ( zone );
    String output = dateTime.toLocalTime ().toString ();
    

    dump to console.

    System.out.println ( "zone: " + zone + " | dateTime: " + dateTime + " | output: " + output );
    

    When run…

    zone: America/Denver | dateTime: 2016-07-11T20:50:17.668-06:00 | output: 20:50:17.668

    Count Since Epoch

    I strongly recommend against tracking by time by count-since-epoch. But if necessary, you can extract Joda-Time’s internal milliseconds-since-epoch (Unix time, first moment of 1970 UTC) by calling the getMillis method on a DateTime.

    Note the use of the 64-bit long rather than 32-bit int primitive types.

    In java.time. Keep in mind that you may be losing data here, as java.time holds a resolution up to nanoseconds. Going from nanoseconds to milliseconds means truncating up to six digits of a decimal fraction of a second (3 digits for milliseconds, 9 for nanoseconds).

    long millis = Instant.now ().toEpochMilli ();
    

    In Joda-Time.

    long millis = DateTime.now( denverTimeZone ).getMillis();
    
    0 讨论(0)
  • 2020-11-30 10:26
    Calendar cal = Calendar.getInstance();
    TimeZone tz = cal.getTimeZone();
    Log.d("Time zone","="+tz.getDisplayName());
    
    0 讨论(0)
  • 2020-11-30 10:28

    Cleanest way is with SimpleDateFormat

    SimpleDateFormat = SimpleDateFormat("MMM\nd\nh:mm a", Locale.getDefault())
    

    or you can specify the Locale

    0 讨论(0)
  • 2020-11-30 10:31

    One way to deal with time zone and milliseconds values:

    val currentDateTime = Calendar.getInstance().apply {
            timeZone?.let {
                val tzCalendar = Calendar.getInstance(it)
                this.set(Calendar.HOUR_OF_DAY, tzCalendar.get(Calendar.HOUR_OF_DAY))
                this.set(Calendar.MINUTE, tzCalendar.get(Calendar.MINUTE))
            }
        }.time
    

    This way you're getting time in milliseconds for the specific timezone.

    0 讨论(0)
  • 2020-11-30 10:38

    I got it to work like this :

    TimeZone tz = TimeZone.getTimeZone("GMT+05:30");
    Calendar c = Calendar.getInstance(tz);
    String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+
                String.format("%02d" , c.get(Calendar.MINUTE))+":"+
    .                   String.format("%02d" , c.get(Calendar.SECOND))+":"+
        .           String.format("%03d" , c.get(Calendar.MILLISECOND));
    

    Also, every other time conversion based on this date should also be used with this timezone, otherwise, the default timezone of device will be used and the time will be converted based on that timezone.

    0 讨论(0)
  • 2020-11-30 10:41

    Try this:

    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    df.setTimeZone(TimeZone.getTimeZone("YOUR_TIMEZONE"));
    String strDate = df.format(date);
    

    YOUR_TIMEZONE may be something like: GMT, UTC, GMT-5, etc.

    0 讨论(0)
提交回复
热议问题