Here is the answer of 2017.
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 more naturally this code expresses intent.
Code prints
GMT: 2011-03-23 16:40:44 Europe/Madrid: 2011-03-23 17:40:44
(with tabbed size 8 it aligns well, but StackOverflow seems to use tab size 4).
I swapped 23 and 03 in your input line, I suppose you intended to do this. By the way, I did not catch your mistake, it was LocalDateTime.parse() , throwing an exception because there is no 23rd month. Also in this regard, modern classes are more useful than obsolete ones.
Joda-Time? Vasily Burka's answer mentions and recommends both java.time , which I use, and Joda-Time. Although Joda-Time already significantly improves the obsolete classes used in the question ( SimpleDateFormat , Calendar , GregorianCalendar ), it is already in maintenance mode; no further development is expected. java.time extremely inspired by Joda-Time. For the new code, I see no reason why you should not prefer java.time .
Ole vv
source share