简体   繁体   中英

Date TimeZone conversion in java?

I was looking for the simplest way to convert a date an time from GMT to my local time. Of course, having the proper DST dates considered and as standard as possible.

The most straight forward code I could come up with was:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String inpt = "2011-23-03 16:40:44";
Date inptdate = null;
try {
    inptdate = sdf.parse(inpt);
} catch (ParseException e) {e.printStackTrace();}   
Calendar tgmt = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
tgmt.setTime(inptdate);

Calendar tmad = new GregorianCalendar(TimeZone.getTimeZone("Europe/Madrid"));
tmad.setTime(inptdate);

System.out.println("GMT:\t\t" + sdf.format(tgmt.getTime()));
System.out.println("Europe/Madrid:\t" + sdf.format(tmad.getTime()));

But I think I didn't get the right concept for what getTime will return.

The catch here is that the DateFormat class has a timezone. Try this example instead:

    SimpleDateFormat sdfgmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdfgmt.setTimeZone(TimeZone.getTimeZone("GMT"));

    SimpleDateFormat sdfmad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdfmad.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

    String inpt = "2011-23-03 16:40:44";
    Date inptdate = null;
    try {
        inptdate = sdfgmt.parse(inpt);
    } catch (ParseException e) {e.printStackTrace();}

    System.out.println("GMT:\t\t" + sdfgmt.format(inptdate));
    System.out.println("Europe/Madrid:\t" + sdfmad.format(inptdate));

Here is the 2017 answer.

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String inpt = "2011-03-23 16:40:44";

    ZonedDateTime madridTime = LocalDateTime.parse(inpt, dtf)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(ZoneId.of("Europe/Madrid"));

    System.out.println("GMT:\t\t" + inpt);
    System.out.println("Europe/Madrid:\t" + madridTime.format(dtf));

Please enjoy how much more naturally this code expresses the intent.

The code prints

GMT:        2011-03-23 16:40:44
Europe/Madrid:  2011-03-23 17:40:44

(with tab size of 8 it aligns nicely, but StackOverflow seems to apply a tab size of 4).

I swapped 23 and 03 in your input string, I believe you intended this. BTW, it wasn't me catching your mistake, it was LocalDateTime.parse() throwing an exception because there is no 23rd month. Also in this respect the modern classes are more helpful than the outdated ones.

Joda-Time? Basil Bourque's answer mentions and recommends both java.time , which I am using, and Joda-Time. While Joda-Time is already a sizeable improvement over the outdated classes used in the question ( SimpleDateFormat , Calendar , GregorianCalendar ), it is by now in maintenance mode; no greater further development is expected. java.time is hugely inspired by Joda-Time. For new code, I see no reason why you shouldn't prefer java.time .

The simplest way is to use a decent date-time library rather than the notoriously troublesome java.util.Date and .Calendar classes. Instead use either Joda-Time or the java.time package found in Java 8.

Joda-Time

String input = input.replace( " ", "T" ).concat( "Z" ) ; // proper ISO 8601 format for a date-time in UTC.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Madrid" );
DateTime dateTime = new DateTime( input, timeZone );
String output = dateTime.toString();

您需要使用DateFormat.setTimeZone()SimpleDateFormat上设置TimeZone

对于输入,您只需将时区添加到字符串中(请注意格式中的“ z”):

new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss z").parse ("2011-23-03 16:40:44 GMT");

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