Java 获取给定时区的当前时间:android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16202956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:46:08  来源:igfitidea点击:

Get current time in a given timezone : android

javaandroidandroid-date

提问by Vishesh Joshi

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

我是 Android 的新手,我目前面临着获取给定时区的当前时间的问题。

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

我以“GMT-7”格式获取时区,即字符串。我有系统时间。

Is there a clean way to get the current time in the above given timezone? Any help is appreciated. Thanks,

有没有一种干净的方法来获取上述给定时区的当前时间?任何帮助表示赞赏。谢谢,

edit : Trying to do this :

编辑:尝试这样做:

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

采纳答案by Vishesh Joshi

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.

此外,基于此日期的所有其他时间转换也应与此时区一起使用,否则将使用设备的默认时区并根据该时区转换时间。

回答by Flávio Faria

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.

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

回答by aran

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Log.d("Time zone","="+tz.getDisplayName());

回答by Basil Bourque

java.time

时间

Both the older date-time classes bundled with Java and the third-party Joda-Time library have been supplanted by the java.timeframework 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-Backportand further adapted to Android in ThreeTenABP.

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

By the way, never refer to an offset-from-UTCwith 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.

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

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

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

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

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

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

如果您有一个完整的时区,它是一个偏移量加上一组用于处理夏令时 (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 );

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

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

See this code in action in Ideone.com.

在 Ideone.com 中查看此代码的运行情况

Joda-Time

乔达时间

You can use Joda-Time2.7 in Android. Makes date-time work much easier.

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

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

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

Count Since Epoch

自纪元以来的计数

I strongly recommend againsttracking 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 getMillismethod on a DateTime.

我强烈建议不要按自纪元以来的时间进行跟踪。但是,如果有必要,你可以提取乔达时间的内部毫秒纪元以来(Unix时间通过调用UTC 1970年的第一刻)getMillis上的一个方法DateTime

Note the use of the 64-bit longrather than 32-bit intprimitive types.

请注意使用 64 位long而不是 32 位int原始类型

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

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

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

In Joda-Time.

在乔达时代。

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

回答by igork

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

回答by Tang Chanrith

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

是的你可以。通过调用 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;
}

回答by Rajesh Nasit

 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

根据您的选择,TimeZoneID 可以是以下之一

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

回答by Justcurious

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.

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

     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

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

回答by Kyle

Cleanest way is with SimpleDateFormat

最干净的方法是使用 SimpleDateFormat

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

or you can specify the Locale

或者您可以指定区域设置

回答by Goran Devs

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.

通过这种方式,您可以获得特定时区的时间(以毫秒为单位)。