如何使用 java 中的默认 GMT 时间创建日历

How to create a calendar with the default GMT hours in java

我从服务器收到了一个很长的日期,我必须将其解析为一个日期。我正在使用日历来这样做。

问题是 long 是从服务器转换过来的(它有用户本地时间),但我把它作为默认的 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());

对不起,我误会了 我猜你有时间以毫秒为单位。那么,从那里开始:

Date dateCreated = new Date(timeInMilliseconds);

然后当您创建日历时,只需在设置时间后设置时区,因为 setTimeInMillis 会覆盖您之前在创建实例时设置的时区

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(new java.util.Date().getTime());
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));

就是这样

使用 SimpleDateFormat 而不是 Calendar。下面的代码显示了正确的结果。

    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    String result = df.format(dateLong);
    System.out.println(result);

其他答案已经提供了 CalendarSimpleDateFormat 的解决方案。我只想添加另一种方法。

旧的 类(DateCalendarSimpleDateFormat)有 lots of problems and design issues,它们将被新的 API 取代。

在 Android 中(如果您愿意为项目添加依赖项 - 在这种情况下完全值得,IMO),您可以使用 ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it ).

首先,您可以使用 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