java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API: There are two things that need to be addressed:
- Change the Date-Time string to have the standard name of the timezone which is
Europe/Paris
.
- Build a case-insensitive parser using
DateTimeFormatterBuilder
.
Demo:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "18-sep-2009 10:25:11 Europe/Paris";
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-uuuu HH:mm:ss zzzz")
.toFormatter(Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
}
}
Output:
2009-09-18T10:25:11+02:00[Europe/Paris]
ONLINE DEMO
However, if changing the Date-Time string is not in your control i.e. you want to go with Romance Daylight Time
itself, java.time
provides you with a clean way to handle it. All you need to prepare before using java.time
API is a Map
with all such non-standard timezone names.
Demo:
import java.text.ParsePosition;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String strDateTime = "18-sep-2009 10:25:11 Romance Daylight Time";
Map<String, String> zoneIdMap = Map.of("Romance Daylight Time", "Europe/Paris");
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-uuuu HH:mm:ss")
.toFormatter(Locale.ENGLISH);
ZonedDateTime zdt = LocalDateTime.from(dtf.parse(strDateTime, new ParsePosition(0)))
.atZone(ZoneId.of("Romance Daylight Time", zoneIdMap));
System.out.println(zdt);
}
}
Output:
2009-09-18T10:25:11+02:00[Europe/Paris]
ONLINE DEMO
Learn more about 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.