Date format: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
Input date: "2017-09-18T03:08:20.888+0200"
Problem: I need retrieve timezone offset from the input String and print the parsed date in this timezone. In other words, I need output to be the same as the input.
SimpleDateFormat
parses input date successfully and returns java.util.Date
object. As we know, Date does not have timezone field. SimpleDateFormat
converts parsed date to its timezone, which is, by default, system timezone. When I print this date, it is printed in System timezone.
Simple demo
private static void runDemoTask() throws ParseException {
final String dateTimeTimezoneFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
final SimpleDateFormat inputSdf = new SimpleDateFormat(dateTimeTimezoneFormat);
final String inputDate = "2017-09-18T01:08:20.888+0200";
Date parsedDate = inputSdf.parse(inputDate);
final SimpleDateFormat outputSdf = new SimpleDateFormat(dateTimeTimezoneFormat);
//outputSdf.setTimeZone("X_TIMEZONE_WHICH_I_NEED");
String output = outputSdf.format(parsedDate);
System.out.println(output);
}
Output
Mon Sep 18 00:08:20 GMT+01:00 2017
Note, output date has system timezone, which is different from input string.
Note, I will not use java.time, Joda Time and other libraries because I need to support existing code.
Possible unpleasant solution
I tried to use regular expression to retrieve sign and offset.
private static String parseTimeZone(String input) {
final int singGroup = 1;
final int offsetGroup = 2;
final String timezonePatternStr = "([+-])(\\d{4})$";
final Pattern timezonePattern = Pattern.compile(timezonePatternStr);
Matcher matcher = timezonePattern.matcher(input);
if (matcher.find()) {
String sign = matcher.group(singGroup);
String offset = matcher.group(offsetGroup);
System.out.println(sign + " " + offset);
}
return "";
}
It prints
+ 0200