Get current time in a given timezone : android

后端 未结 10 1957
悲哀的现实
悲哀的现实 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:41

    Set the timezone to formatter, not calendar:

    public String getTime(String timezone) {
        Calendar c = Calendar.getInstance();
        Date date = c.getTime(); //current date and time in UTC
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        df.setTimeZone(TimeZone.getTimeZone(timezone)); //format in given timezone
        String strDate = df.format(date);
        return strDate;
    }
    
    0 讨论(0)
  • 2020-11-30 10:43

    I found a better and simpler way.

    First set time zone of app using

        TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
    

    And then call Calander to get date internally it uses default timezone set by above through out app.

         Calendar cal = Calendar.getInstance();
         Log.d("Los angeles time   ",cal.getTime().toString());
    

    It will give current time based on time zone.

    D/Los angeles time: Thu Jun 21 13:52:25 PDT 2018

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

    Yes, you can. By call TimeZone setDefault() method.

    public String getTime(String timezone) {
        TimeZone defaultTz = TimeZone.getDefault();
    
        TimeZone.setDefault(TimeZone.getTimeZone(timezone));
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        String strDate = date.toString();
    
        // Reset Back to System Default
        TimeZone.setDefault(defaultTz);
    
        return strDate;
    }
    
    0 讨论(0)
  • 2020-11-30 10:46
     TimeZone tz = TimeZone.getTimeZone(TimeZoneID);
     Calendar c= Calendar.getInstance(tz);
     String time=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date(cal.getTimeInMillis()));
    

    TimeZoneID can be one of from below as per as your choice

    String[] ids=TimeZone.getAvailableIDs();
    

    then time can be get as per accepted answer above

    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));
    
    0 讨论(0)
提交回复
热议问题