![](/img/trans.png)
[英]How to parse the “GMT+hours:minutes” or “GMT-hours:minutes” using SimpleDateFormat in Java (Android)
[英]How to create a calendar with the default GMT hours in java
我要从服务器解析很长时间,必须将其解析为一个日期。 我正在使用日历。
事情是从服务器转换过来的(它具有用户本地时间),但是我将其作为默认的GMT并将其也转换为本地时间。
因此,它转换了两次。 既然我做对了,如何在不将其更改为本地的情况下显示它(默认情况下似乎要这样做)? 我的代码:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(dateLong);
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format1.format(cal.getTime());
代替使用Calendar
使用SimpleDateFormat
。 以下代码向我显示了正确的结果。
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String result = df.format(dateLong);
System.out.println(result);
其他答案已经提供了Calendar
和SimpleDateFormat
解决方案。 我只想添加另一种方法。
旧的类( Date
, Calendar
和SimpleDateFormat
)存在很多问题和设计问题 ,并且已被新的API取代。
在Android中(如果可以将依赖项添加到项目中-在这种情况下,这是完全值得的,IMO),则可以使用ThreeTen Backport ,它是Java 8的新日期/时间类的绝佳反向端口 。 为了使其工作,您还需要ThreeTenABP (更多有关如何在此处使用它的信息 )。
首先,您可以使用org.threeten.bp.Instant
将org.threeten.bp.Instant
值转换为相应的UTC时刻。 然后,使用org.threeten.bp.format.DateTimeFormatter
定义所需日期的格式。 我还使用org.threeten.bp.ZoneOffset
来指示格式化程序应使用UTC中的日期:
long dateLong = System.currentTimeMillis();
// convert long millis value to Instant
Instant instant = Instant.ofEpochMilli(dateLong);
// create formatter in UTC
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
.withZone(ZoneOffset.UTC);
// format it
System.out.println(fmt.format(instant));
输出将类似于:
13/09/2017 11:28:02
抱歉,我误会了您的时间,以毫秒为单位。 好吧,从那里:
Date dateCreated = new Date(timeInMilliseconds);
然后,当您创建日历时,只需在设置时间之后设置时区,因为在创建实例时setTimeInMillis会覆盖您之前的TimeZone设置
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(new java.util.Date().getTime());
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
而已
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.