简体   繁体   中英

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

I'm getting a long from a server that I have to parse into a date. I'm using a calendar to do so.

Thing is that the long came transformed from the server (it have the user local time), but I get it as a default GMT and I also transform it into local time.

So, it transforms twice. Since I get it right, how can I show it without changing it to local (seems to do it by default)? My code:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));           
calendar.setTimeInMillis(dateLong);
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format1.format(cal.getTime());

Instead of using Calendar use SimpleDateFormat . the following code shows me the correct results.

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

The other answers already provide solutions with Calendar and SimpleDateFormat . I'd just like to add another approach.

The old classes ( Date , Calendar and SimpleDateFormat ) have lots of problems and design issues , and they're being replaced by the new APIs.

In Android (if you're ok about adding a dependency to your project - and in this case it's totally worth it, IMO), you can use the 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 here ).

First you can use a org.threeten.bp.Instant to convert the millis value to a corresponding UTC instant. Then you use a org.threeten.bp.format.DateTimeFormatter to define the format you want the date. I also use a org.threeten.bp.ZoneOffset to indicate that the formatter should use the date in 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));

The output will be something like:

13/09/2017 11:28:02

Sorry, I misunderstood I guess you have time in milliseconds. Well, from there:

Date dateCreated = new Date(timeInMilliseconds);

And then when you create the Calendar, just set Timezone after set time, because setTimeInMillis is overriding your previous TimeZone set when you are creating the instance

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

That's it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM