简体   繁体   中英

How to convert a UTC timestamp to local day, hour, minute in Java?

Given then timestamp 1245613885 that is a timestamp in GMT

How do I turn that into Year, Day, Hour, Minute values in Java using the server's local timezone info?

You can use java.util.Calendar for this. It offers a setTimeZone() method (which is by the way superfluous since it by default already picks the system default timezone).

long timestamp = 1245613885;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timestamp * 1000);

int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);

If you'd like to present it in a human readable date string, then I'd suggest SimpleDateFormat for this.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString); // 2009-06-21 15:51:25

(the output is correct as per my timezone GMT-4)

import java.util.Calendar;  
import java.util.TimeZone;

public class Example{
   public static void main(String[] args){
      long utcTimestamp = 1285578547L;
      Calendar cal = Calendar.getInstance(TimeZone.getDefault());
      cal.setTimeInMillis(utcTimestamp * 1000);
      System.out.println(cal.get(Calendar.YEAR));
      System.out.println(cal.get(Calendar.MONTH));
      System.out.println(cal.get(Calendar.DAY_OF_MONTH));
      System.out.println(cal.get(Calendar.DAY_OF_YEAR));
      System.out.println(cal.get(Calendar.HOUR));
      System.out.println(cal.get(Calendar.MINUTE));
   }
}

我会使用像Joda Time这样的东西比JDK Date / Calendar类快得多,而且日期解析也没有线程安全问题(不是你的问题与日期解析有关)

Basically you just need a formatter to do this

Date date = new Date(1245613885L*1000);
SimpleDateFormat formatter = new SimpleDateFormat('MM/dd/yyyy');
System.out.println(formatter.format(date));

tl;dr

Instant                                        // Represent a moment in UTC.
.ofEpochMilli( 1_245_613_885L )                // Parse a count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
.atZone(                                       // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
    ZoneId.of( "Asia/Tokyo" )                  // Or "America/Chicago" etc.
)                                              // Returns a `ZonedDateTime` object.
.format(                                       // Generate text representing the value of our `ZonedDateTime` object.
    DateTimeFormatter
    .ofLocalizedDateTime( FormatStyle.FULL )   // Automatically localize the format and content of the string being generated.
    .withLocale( Locale.CANADA_FRENCH )        // Or Locale.US etc.
)                                              // Returns a `String` object.

jeudi 15 janvier 1970 à 19 h 00 min 13 s heure normale du Japon

java.time

The modern approach uses the java.time classes that supplanted the terrible date-time classes as of the adoption of JSR 310.

If your input 1245613885 is count of milliseconds since the first moment of 1970 in UTC, then parse as an Instant (a moment in UTC).

Instant instant = Instant.ofEpochMilli( 1_245_613_885L ) ;

Generate a string representing the value of that Instant object using standard ISO 8601 format.

String output = instant.toString() ;

Adjust from UTC to the wall-clock time used by the people of a particular region( a time zone).

Specify a proper time zone name in the format of Continent/Region , such as America/Montreal , Africa/Casablanca , or Pacific/Auckland . Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  

If you want to use the JVM's current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Apply a ZoneId to the Instant to get a ZonedDateTime .

ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment as the `instant`, but different wall-clock time.

Generate a string representing the value of that ZonedDateTime object using standard ISO 8601 format extended to append the name of the zone in square brackets.

String output = zdt.toString() ;

For other formats, either specify your own custom formatting pattern or let java.time automatically localize. For either route, use DateTimeFormatter . Search Stack Overflow as this has been handled many times already.

Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"), Locale.US);
calendar.setTimeInMillis(1245613885 * 1000);
int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DAY_OF_YEAR);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);

Change the TimeZone value you're passing into the Calendar object's constructor if you need a different time zone.

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