java.time
The legacy date-time API (java.util
date-time types and their formatting type, SimpleDateFormat
) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
And the locale was "Europe/London", 'date' should return GMT and date2
should return "BST"
Note that Europe/London
is a time zone (ZoneId
), not a Locale
. Java SE 8 date-time API (java.time
) provides us with ZonedDateTime
which automatically adjusts the timezone offset as per the DST transition.
Demo:
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("d/M/u", Locale.ENGLISH);
LocalDate date = LocalDate.parse("01/01/2014", dtfInput);
LocalDate date2 = LocalDate.parse("01/07/2014", dtfInput);
ZoneId zoneId = ZoneId.of("Europe/London");
ZonedDateTime zdt = date.atStartOfDay(zoneId);
ZonedDateTime zdt2 = date2.atStartOfDay(zoneId);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("dd/MM/uuuu'['z']'", Locale.ENGLISH);
System.out.println(zdt.format(dtfOutput));
System.out.println(zdt2.format(dtfOutput));
}
}
Output:
01/01/2014[GMT]
01/07/2014[BST]
Learn more about java.time
, the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.