【问题标题】:Get current time in a given timezone : android获取给定时区的当前时间:android
【发布时间】:2013-04-18 15:38:03
【问题描述】:

我是 Android 新手,目前在给定时区的情况下获取当前时间时遇到问题。

我得到“GMT-7”格式的时区,即字符串。 我有系统时间。

是否有一种简洁的方法可以在上述给定时区中获取当前时间? 任何帮助表示赞赏。 谢谢,

编辑: 尝试这样做:

public String getTime(String timezone) {
    Calendar c = Calendar.getInstance();
    c.setTimeZone(TimeZone.getTimeZone(timezone));
    Date date = c.getTime();
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    String strDate = df.format(date);
    return c.getTime().toString();
}

【问题讨论】:

  • “当前时间”是指没有日期的时间,或者您是指仅日期,如您的示例 SimpleDateFormat 所见,还是您的意思是日期时间在最后一行看到return?

标签: java android android-date


【解决方案1】:

在 Kotlin 中:

 val mTime: Calendar = Calendar.getInstance()
 val timeZone = TimeZone.getDefault().displayName // based on the device time zone it will calculate.

输出:

IST // it will return device time zone

【讨论】:

    【解决方案2】:
    // Backup the system's timezone
    TimeZone backup = TimeZone.getDefault();
    
    String timezoneS = "GMT-1";
    TimeZone tz = TimeZone.getTimeZone(timezoneS);
    TimeZone.setDefault(tz);
    // Now onwards, the default timezone will be GMT-1 until changed again
    
    Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
    String timeS = String.format("Your time on %s:%s", timezoneS, date);
    System.out.println(timeS);
    
    // Restore the original timezone
    TimeZone.setDefault(backup);
    System.out.println(new Date());
    

    【讨论】:

      【解决方案3】:

      处理时区和毫秒值的一种方法:

      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
      

      这样您就可以获得特定时区的毫秒数。

      【讨论】:

        【解决方案4】:

        我让它像这样工作:

        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));
        

        另外,每隔一次基于此日期的时间转换也应与此时区一起使用,否则将使用设备的默认时区,并且将基于该时区转换时间。

        【讨论】:

        • 如何获得实际的日期而不是字符串?
        • 这仅适用于 5:30 时区。如果我们希望应用程序选择他的手机设置中指定的时区,解决方案是什么?喜欢:如果来自俄罗斯的人打开应用程序,他应该会得到俄罗斯时区。
        • @COSTA 您可以使用TimeZone timeZone = TimeZone.getDefault(); 获取应用运行位置的时区。
        • 它返回设备时间,如果用户更改设备时间,我如何从 timeZone 获得准确时间
        • @HammadNasir TimeZone.getDefault();返回一个字符串“+0530”。如何将其格式化为“+05:30”?
        【解决方案5】:

        我找到了一种更好更简单的方法。

        应用程序使用的第一个设置时区

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

        然后调用 Calander 在内部获取日期,它使用上面通过应用程序设置的默认时区。

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

        它会根据时区给出当前时间。

        D/洛杉矶时间:2018 年 6 月 21 日星期四 13:52:25 PDT

        【讨论】:

        • 使用给定方法设置时区后,calender.getTime 将提供所需的 Date 实例。谢谢。
        【解决方案6】:

        最干净的方法是使用 SimpleDateFormat

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

        或者您可以指定语言环境

        【讨论】:

          【解决方案7】:
           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 可以根据您的选择为以下之一

          String[] ids=TimeZone.getAvailableIDs();
          

          然后可以根据上面接受的答案获得时间

          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));
          

          【讨论】:

            【解决方案8】:

            是的,你可以。通过调用 TimeZonesetDefault() 方法。

            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;
            }
            

            【讨论】:

            • 由于 default 是关键字,因此用作 TimeZone timezone = TimeZone.getDefault();
            【解决方案9】:

            java.time

            与 Java 捆绑在一起的旧日期时间类和第三方 Joda-Time 库都已被 Java 8 及更高版本中内置的 java.time 框架所取代。这些类取代了旧的麻烦的日期时间类,例如java.util.Date。见Oracle Tutorial。大部分 java.time 功能在 ThreeTen-Backport 中向后移植到 Java 6 和 7,并在 ThreeTenABP 中进一步适应 Android。

            顺便说一句,永远不要使用-7 等单个小时数来引用offset-from-UTC,因为这是非标准的,并且与各种协议和库不兼容。始终用零填充第二个数字,例如 -07

            如果您只有一个偏移量而不是时区,请使用OffsetDateTime 类。

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

            当前时间在-07:00: 19:41:36.525

            如果您有一个完整的时区,它是一个偏移量加上一组用于处理诸如夏令时 (DST) 等异常的规则,而不仅仅是与 UTC 的偏移量,请使用ZonedDateTime 类。

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

            美国/丹佛当前时间:20:41:36.560

            this code in action in Ideone.com

            乔达时间

            您可以在 Android 中使用Joda-Time 2.7。使日期时间工作更容易。

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

            转储到控制台。

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

            运行时……

            区域:美国/丹佛 |日期时间:2016-07-11T20:50:17.668-06:00 |输出:20:50:17.668

            自纪元以来的计数

            I strongly recommend against 按时间跟踪 count-since-epoch。但如有必要,您可以通过在 DateTime 上调用 getMillis 方法来提取 Joda-Time 的内部毫秒自纪元(Unix time,1970 UTC 的第一时刻)。

            注意使用 64 位 long 而不是 32 位 int primitive types

            在 java.time 中。请记住,您可能会在这里丢失数据,因为 java.time 的分辨率高达纳秒。从纳秒到毫秒意味着最多截断一秒十进制小数的六位数字(毫秒为 3 位,纳秒为 9 位)。

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

            在乔达时代。

            long millis = DateTime.now( denverTimeZone ).getMillis();
            

            【讨论】:

            • 我如何在毫秒内得到这个?
            • @KarlMorrison 使用毫秒计数通常是个坏主意(搜索 StackOverflow 进行讨论),但如果你坚持看我的编辑。
            • @NarayanaJ 我刚刚复制并粘贴了我刚刚在 Java 8 中使用 Joda-Time 库 2.9.4 运行的 Joda-Time 代码。此外,您应该知道 Joda-Time 团队建议迁移到 java.time 类。我在顶部添加了整个部分,展示了如何在 java.time 中完成相同的工作。你可以锻炼that java.time code at Ideone.com
            • 如果设备(移动/系统)时间错误,上述方法均无效。如何获得正确的时间认为系统时间是错误的?
            • @PrashanthDebbadwar 在 Stack Overflow 上多次提问和回答,例如 thisthisthis。请养成搜索 Stack Overflow 的习惯,因为它更像是维基百科,而不是讨论组。
            【解决方案10】:

            将时区设置为格式化程序,而不是日历:

            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;
            }
            

            【讨论】:

            • 如何获得实际的日期而不是字符串?
            【解决方案11】:

            试试这个:

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

            YOUR_TIMEZONE 可能类似于:GMT、UTC、GMT-5 等。

            【讨论】:

            • 它对我不起作用。我试过 GMT+5 , GMT+7。但它一直在给我当前时区的当前时间,而不是我经过的时间。
            • 如果你打算返回 c.getTime().toString() 你不需要 DateFormat 的东西。
            • 抱歉,c.getTime() 不会将时区传递给 Date 对象。试试c.toString()
            • 您应该按名称而不是 3 字母代码或偏移编号来引用时区。三字母代码不规范,重复很多。如果您使用名称而不是偏移量,您的日期时间库可能有助于解决夏令时和其他异常情况。请参阅this list 的名称。
            • 你如何得到一个实际的日期而不是一个字符串?
            猜你喜欢
            • 2012-02-29
            • 2017-04-30
            • 1970-01-01
            • 2012-03-23
            • 1970-01-01
            • 1970-01-01
            • 2017-09-18
            • 2011-12-21
            相关资源
            最近更新 更多