I know there are similar questions like this, but I wasn't quite able to find the example similar to mine. I learned about LocalDateTime and ZonedDateTime but I don't know how to tell my ZonedDateTime what's assumed timezone of parsed date.
I'm migrating from Java 7 to Java 8. In my code, I have a method like this:
public String changeTZ(String tzFrom, String tzTo, String dateToChange) {
ZoneId zoneFrom = ZoneId.of(tzFrom);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat.toPattern());
LocalDateTime localtDateAndTime = LocalDateTime.parse(dateToChange, formatter);
ZonedDateTime dateAndTimeINeed = ZonedDateTime.of(localtDateAndTime, zoneFrom );
ZonedDateTime rezDate = dateAndTimeINeed.withZoneSameInstant(ZoneId.of(tzTo));
return formatter.format(rezDate);
}
Example usage is:
String rez = changeTZ("CEST", "UTC", "2017-08-10 14:23:58");
As you can see it receives datetime in form of string, timezone date is in tzFrom variable and TZ I need (toTo variable).
Code which does that in Java 7 is absurd and complex so I won't enlist it here. Can you please tell me how to achieve the same in Java 8 without changing method interface (arguments and return type)? What about DST? Is it handled automatically in Java 8?
Note that method also supports timezones in form of "CEST", "CET", "UTC" as well as standard ones like "Europe/London".
Java 8 uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the short abbreviations (like CEST or PST) because they are ambiguous and not standard.
Actually, those names don't work with ZoneId mainly because of this ambiguity (CST, for example, can be "Central Standard Time", "Cuba Standard Time" or "China Standard Time"). Actually, some of them might work due to retro-compatibility reasons, but it's not guaranteed to work with all of them.
I'm assuming that CEST is the Central European Summer Time. There are lots of different countries (and timezones) that are currently in CEST, so the API can't decide which timezone to choose if you just pass "CEST" to it.
That's because a timezone contains all the different offsets a region had during its history. There may be lots of countries using CEST today, but their history differs in the past (some might had DST in different years, or used a different offset and then changed, etc), and that's why they have one timezone for each.
To use such short names (like CEST), though, you can define some defaults for each one (which will be an arbitrary choice) and put these choices in a map:
// map of custom zone names
Map<String, String> map = new HashMap<>();
// setting my arbitrary choices for each name
map.put("CEST", "Europe/Berlin"); // Berlin during DST period
map.put("CET", "Europe/Berlin"); // Berlin during non-DST period
// ... and so on
Then you can use this map to create the ZoneId:
// use the custom map to create the ZoneId
ZoneId zoneFrom = ZoneId.of(tzFrom, map);
...
// use the custom map to create the ZoneId
ZonedDateTime rezDate = dateAndTimeINeed.withZoneSameInstant(ZoneId.of(tzTo, map));
I've chosen Europe/Berlin, but of course you can change it to whatever timezone you need. You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
Using the map above:
System.out.println(changeTZ("CEST", "UTC", "2017-08-10 14:23:58"));
This code outputs:
2017-08-10 12:23:58
Note that 14:23 in CEST (which I chose to be Europe/Berlin) is 12:23 in UTC, which is correct because in August Berlin is in DST (offset is +02:00).
ZoneId and ZonedDateTime classes handle DST effects automatically. You can check this by choosing a date in January (when DST is not in effect in Berlin):
// January is not DST, so use CET
System.out.println(changeTZ("CET", "UTC", "2017-01-10 14:23:58"));
The output is:
2017-01-10 13:23:58
In January Berlin is not in DST, so the offset is +01:00, then 14:23 in Berlin becomes 13:23 in UTC.
Of course the ideal is to always use the full names (like Europe/Berlin), but the custom map is an alternative if you don't have control over the inputs.
Java 8 also has a built-in predefined map, but as any other predefined stuff, the choices are arbitrary and not necessarily the ones you need.
This solution uses the IANA timezones names mentioned by Hugo in the comments to get the ZoneId (more details here). Will throw an exception if you use it with CEST.
public static String changeTZ(String tzFrom, String tzTo, String dateToChange){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of(tzFrom));
ZonedDateTime zdt = ZonedDateTime.parse(dateToChange, dtf);
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of(tzTo));
return zdt.format(dtf2);
}
Use like:
String rez = changeTZ("US/Alaska", "Europe/Berlin", "2017-08-10 14:23:58");
Here is a class that does the job.
public class TimeZoneConverter {
private static String datePattern = "yyyy-MM-dd HH:mm:ss";
public static void main(String[] args) throws ParseException {
String sourceDate = "2017-02-27 16:00:00";
String resultDate = convertTimeZone("EET", "UTC", sourceDate);
System.out.println("EET: "+ sourceDate);
System.out.println("UTC: "+ resultDate);
}
public static String convertTimeZone(String timeZoneFrom, String timeZoneTo, String date) throws ParseException {
long timestamp = stringToTimestamp(date, timeZoneFrom);
String result = timestampToString(timestamp, timeZoneTo);
return result;
}
public static long stringToTimestamp(String time, String timeZone) throws ParseException {
DateFormat format = getDateFormat(timeZone);
return format.parse(time).getTime();
}
public static String timestampToString(long timestamp, String timeZone) {
DateFormat format = getDateFormat(timeZone);
return format.format(new Date(timestamp));
}
private static DateFormat getDateFormat(String timeZone) {
DateFormat format = new SimpleDateFormat(datePattern);
format.setTimeZone(TimeZone.getTimeZone(timeZone));
return format;
}
}
Related
This question already has answers here:
Convert date string (EST) to Java Date (UTC)
(2 answers)
Convert Calender to Date according to timezone [duplicate]
(1 answer)
Closed 3 days ago.
I have a string with value "25/12/2021" and I want to convert this string into a date format which has a New York timezone.
I am new to Java dates
I tried the below:
SimpleDateFormat zdate = new SimpleDateFormat("dd/MM/yyyy");
zdate.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date zdate2 = zdate.parse("25/12/2021")
but the zdate2 object has the date in my local timezone rather than the New_York timezone.
What am I doing wrong here?
If you are not forced to use java.util.Date, which itself does not have any zone, you could have your requirement met by implementing with java.time:
You just have to
parse it to a LocalDate, a class only having year, month of year and day of month
append a time of day
append the zone
Here's an example…
public static void main(String[] args) throws ParseException {
// example input
String input = "25/12/2021";
// create a pattern handler for parsing
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// create the zone
ZoneId americaNewYork = ZoneId.of("America/New_York");
// parse the String to a LocalDate, then add time of day and zone
ZonedDateTime result = LocalDate.parse(input, dtf)
.atStartOfDay(americaNewYork);
System.out.println(result);
}
Output:
2021-12-25T00:00-05:00[America/New_York]
Small protest about parse() on time objects, the following is what it really takes to assure creation from String information that parse() methods continually reject !!!
bash-5.1$ javac ZoneParse.java
Note: ZoneParse.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
bash-5.1$ java ZoneParse
24 Dec 2021 13:00:00 GMT
bash-5.1$
It will be something alike the following if safe...
import java.time.*;
public class ZoneParse{
public ZoneParse(){
String[] dt = ("25/12/2021").split("/");
ZonedDateTime ztm = (LocalDate.of(new Integer(dt[2]).intValue(),new Integer(dt[1]).intValue(),new Integer(dt[0]).intValue())).atStartOfDay(ZoneId.systemDefault());
System.out.println((java.util.Date.from( (ztm.withZoneSameInstant((ZoneId)ZoneId.of("America/New_York")).toInstant()))).toGMTString());
}//enconstr
public static void main(String[] args){
new ZoneParse();
}//enmain
}//enclss
NOTE withZoneSameInstant() changes both the time and the zone.
withZoneSameLocal() only retags the time as belonging as another time zone
The updated time library since around java 8 is quicker
This following link is a library with some time assistance under construction avoids parse() as much as possible including a pair of methods of String fill in arguments to create a timedate.
https://drive.google.com/file/d/1gjHmdC-BW0Q2vXiQYmp1rzPU497sybNy/view?usp=share_link
The below erroneous code is because parse() is probably one of the WORST explained methods in the docs, it generally requires a few different pages each of different sections to get any explanation of how to use it.
ZonedDateTime ztm = ZonedDateTime.parse("25/12/2021");
Instant it = (ztm.withZoneSameInstant((ZoneId)ZoneId.of("America/New_York"))).toInstant();
java.util.Date date = java.util.Date.from(it);
SimpleDateFormat zdate = new SimpleDateFormat("dd/MM/yyyy");
zdate.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date zdate2 = zdate.parse("25/12/2021")
Remember the four 'y' letters in format
I have some logs and each log message has a timestamp, so I would like to display log message's timestamp in a user-friendly format in Java 8 with the java.time API.
For example, let's say that I have :
a List<Long> that stores all my log timestamps.
a ZoneId that describes the zone I want to use to convert timestamps. Actually, it's Europe/Paris so I have to consider Daylight Saving Time (DST for short).
a DateTimeFormatter that describes the string format I want.
Then, I would like to convert each timestamps in my list to a String that describes this timestamp in my zone, knowing that the offset may differ between 2 timestamps due to DST.
How can I do that ?
The java.time API's ZonedDateTime class automatically takes care of DST. As such, here is a sample implementation.
public static void main(String[] args) {
List<Long> timestamps = new ArrayList<>();
List<String> result = timestamps.stream()
.map(timestamp -> convert(timestamp))
.collect(Collectors.toCollection(ArrayList::new));
}
public static String convert(Long epochMilli) {
Instant now = Instant.ofEpochMilli(epochMilli);
ZoneId zoneId = ZoneId.of("Europe/Paris");
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now, zoneId);
DateTimeFormatter isoDateFormatter = DateTimeFormatter.ISO_DATE;
return zonedDateTime.format(isoDateFormatter);
}
I have a problem in displaying the date in my Application.
I am getting timestamp as:
2017-08-02T06:05:30.000Z
But as per this the actual time is:
2017:08:02 11:35 AM
But after converting using my code it displays the time as:
6:00 am
How to show it as current time?
My code is given below:
private static SimpleDateFormat timestampformat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.mmm'Z'");
private static SimpleDateFormat sdftimeformat = new SimpleDateFormat("HH:mm a");
private static SimpleDateFormat getSdftimeformat() {
return sdftimeformat;
}
public static String timeStampConvertToTime(String time) {
Date date1 = null;
try {
date1 = timestampformat.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedTime = getSdftimeformat().format(date1);
return formattedTime;
}
The first thing is that you're using mm:ss.mmm in your format. According to SimpleDateFormat javadoc, m represents the minutes, so you must change it to mm:ss.SSS because S represents the milliseconds.
Another detail is that the Z in the end is the timezone designator for UTC and it can't be ignored (at least it shouldn't). You must use the corresponding pattern for that, which is X:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date = sdf.parse("2017-08-02T06:05:30.000Z");
PS: the X pattern was introduced in Java 7. If you're using Java <= 6, the only alternative is to treat Z as a literal (an ugly workaround, I admit) and set the UTC as the timezone used by the parser:
// treat "Z" as literal
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// use UTC as timezone
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2017-08-02T06:05:30.000Z");
With this, the date will have the value corresponding to 06:05 in UTC. To format the time to your timezone, you must use another SimpleDateFormat with the corresponding timezone:
// output format: hour:minute AM/PM
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
// assuming a timezone in India
outputFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
System.out.println(outputFormat.format(date));
The output will be:
11:35 AM
If you don't set a timezone, it'll use the system's default. But the default can be changed without notice, even at runtime, so it's better to explicity set a specific timezone as above.
I also used java.util.Locale to set the language to English, because some locales can have different symbols for AM/PM. If you don't specify one, it'll use the system default and it's not guaranteed to be one in which the symbols are the ones you need (some locales uses "a.m./p.m." or another different formats, so it's better to use an explicit locale).
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
To parse the input you can use the ZonedDateTime class, which has full support to timezones and it makes the conversion to another zones very easy. Then you use a DateTimeFormatter to format the output:
// parse the input
ZonedDateTime parsed = ZonedDateTime.parse("2017-08-02T06:05:30.000Z");
// convert to another timezone
ZonedDateTime z = parsed.withZoneSameInstant(ZoneId.of("Asia/Kolkata"));
// format output
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
System.out.println(fmt.format(z));
The output will be:
11:35 AM
If the input always has Z in the end, you can also use the Instant class:
// parse the input
Instant instant = Instant.parse("2017-08-02T06:05:30.000Z");
// convert to a timezone
ZonedDateTime z = instant.atZone(ZoneId.of("Asia/Kolkata"));
Note that I used hh for the hours: this will format using values from 1 to 12 (it makes sense because I'm also using the AM/PM designators). If you want values from 0 to 23, use HH instead - check the javadoc for more details.
Also note that the API uses IANA timezones names (always in the format Region/City, like Asia/Kolkata or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or IST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
You can also use the system's default timezone with ZoneId.systemDefault(), but this can be changed without notice, even at runtime, so it's better to explicity use a specific one.
You need to use SimpleDateFormat class and specify the format you want to parse from , like this :
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
long timeStamp = sdf.parse('your_timestamp').getTime();
SimpleDateFormat currentDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a", Locale.getDefault());
String time =currentDateFormat.format(timeStamp); // Formatted time in string form
try this your will get result
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
// set your format in df variable
SimpleDateFormat df = new SimpleDateFormat(
"HH:mm a");
try {
cal.setTime('your value');
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String localtime = df.format(cal.getTime());
use this for get current time.
Calendar cal =
Calendar.getInstance(TimeZone.getTimeZone("GMT+5:30"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("HH:mm a");
// you can get seconds by adding "...:ss" to it
date.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
String localTime = date.format(currentLocalTime);
change time zone to your time zone
I assume the Z in Rose's timestamp is zulu time, it isn't really correct to hard code the conversion from zulu time to his local time zone (GMT+5:30 we are assuming). It might be OK if it is always returning Z but if it is
military time zones you would need something that can handle all the possible timezones.
This previous question implies there is no built in way to do it. Need to understand where the timestamp is coming from to really answer the question.
I am getting a parse exception when trying to parse the time string 02:22 p.m..
I have the following conversion function:
public static long convertdatetotimestamp(String datestring, String newdateformat, String olddateformat){
SimpleDateFormat originalFormat = new SimpleDateFormat(olddateformat,Locale.ROOT);
SimpleDateFormat targetFormat = new SimpleDateFormat(newdateformat,Locale.ROOT);
Date date = null;
try {
date = originalFormat.parse(datestring);
String formattedDate = targetFormat.format(date);
Date parsedDate = targetFormat.parse(formattedDate);
long nowMilliseconds = parsedDate.getTime();
return nowMilliseconds;
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
The method is called in another activity with a time format "02:22 p.m.". olddateformat and newdateformat are the same: hh:mm a.
It causes following error in log:
java.text.ParseException: Unparseable date: "02:22 p.m." (at offset 6)
How to resolve this issue? Time is in exactly above mentioned format.
It so happens that a.m. and p.m. are called just this in Gaelic locale. At least on my Java 8. I am far from sure that it will be the case on (all) Android phones, but you may do some experiments with it.
String datestring = "02:22 p.m.";
Locale parseLocale = Locale.forLanguageTag("ga");
DateTimeFormatter originalFormat = DateTimeFormatter.ofPattern("hh:mm a", parseLocale);
System.out.println(LocalTime.parse(datestring, originalFormat));
This prints
14:22
As Hugo so warmly and rightly recommends is his answer, I am using the modern Java date and time API, so you will need ThreeTenABP for the above code. See How to use ThreeTenABP in Android Project. Alternatively you may want to try the same locale with your otherwise outdated SimpleDateFormat.
US Spanish locale shows the same behaviour on my Java 8, so you may try that too: Locale.forLanguageTag("es-US").
I believe that SimpleDateFormat can't be customized to parse the p.m. part (it only recognizes AM or PM).
So one alternative is to remove the dots:
String time = "02:22 p.m.";
SimpleDateFormat format = new SimpleDateFormat("hh:mm a", Locale.ROOT);
date = format.parse(time.replaceAll("\\.", ""));
One detail: to get the nowMilliseconds value, you need all the date fields (day/month/year) and a timezone. As those fields are not in the input String, SimpleDateFormat sets them to January 1st of 1970 (and also set the seconds and milliseconds to zero), and use the system's default timezone.
I'm not sure if this behaviour of getting January 1970 is consistent among all Java versions, which is another problem because you can get different values depending on the environment/device the code is running. Actually, you might have a different result anyway because it uses the system's default timezone and this can vary among different environments.
If I run this code in my machine, it uses my system's default timezone (America/Sao_Paulo), and the result is 62520000. But if I change the timezone to another (let's say, Asia/Kolkata), the result is 31920000. You must be aware of this variation and check if that's what you really need.
Another detail is that, if olddateformat and newdateformat are the same, there's no need to create 2 different formatters.
Java's new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. You'll also need the ThreeTenABP (more on how to use it here).
All the relevant classes are in the org.threeten.bp package.
With this new API, you can customize the text that corresponds to AM/PM using a org.threeten.bp.format.DateTimeFormatterBuilder (so no need to remove the dots manually). And there are specific classes to each case - in this case, the input has only the time fields (hour and minutes), so I'm going to use the org.threeten.bp.LocalTime class (which represents only a time - hour/minute/second/nanosecond - without a date):
String time = "02:22 p.m.";
// map AM and PM values to strings "a.m." and "p.m."
Map<Long, String> map = new HashMap<Long, String>();
map.put(0L, "a.m.");
map.put(1L, "p.m.");
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// hour and minute
.appendPattern("hh:mm ")
// use custom values for AM/PM
.appendText(ChronoField.AMPM_OF_DAY, map)
// create formatter
.toFormatter(Locale.ROOT);
// parse the time
LocalTime parsedTime = LocalTime.parse(time, fmt);
The parsedTime variable will contain the values corresponding to 02:22 PM (and only this value, it has no date fields (day/month/year) nor a timezone).
To get the milliseconds value (number of milliseconds since 1970-01-01T00:00Z), you also need a date (day/month/year) and a timezone. As I said previously, those fields can affect the final value.
In the old API, SimpleDateFormat tries to be "smart" and sets default values for those fields (January 1st of 1970 in the system's default timezone), but the new API is more strict about that and you must tell explicity what date and timezone you want.
In this example, I'm using the Asia/Kolkata timezone but you can change it according to your needs (more on that below):
import org.threeten.bp.LocalDate;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
// timezone for Asia/Kolkata
ZoneId zone = ZoneId.of("Asia/Kolkata");
// current date in Kolkata timezone
LocalDate now = LocalDate.now(zone);
// get the parsed time at the specified date, at the specified zone
ZonedDateTime zdt = parsedTime.atDate(now).atZone(zone);
// get the millis value
long millis = zdt.toInstant().toEpochMilli();
If you want a specific date instead of the current date, you can use LocalDate.of(2017, 5, 20) - this will get May 20th, 2017, for example. With this, you can set the code above to the date and timezone you need.
Note that the API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Asia/Kolkata).
Avoid using the 3-letter abbreviations (like IST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
If you want to emulate exactly what SimpleDateFormat does, you can use LocalDate.of(1970, 1, 1) and use the default timezone with ZoneId.systemDefault() - but this is not recommended, because the system's default can be changed without notice, even at runtime. It's better to explicit what timezone you're using.
Or you can create a formatter that always sets default values for the date (using the org.threeten.bp.temporal.ChronoField class) and always uses the same timezone. So you can parse it directly to a org.threeten.bp.Instant and get the millis value:
String time = "02:22 p.m.";
ZoneId zone = ZoneId.of("Asia/Kolkata");
DateTimeFormatter fmt2 = new DateTimeFormatterBuilder()
// hour and minute
.appendPattern("hh:mm ")
// use custom values for AM/PM (use the same map from previous example)
.appendText(ChronoField.AMPM_OF_DAY, map)
// default value for day: 1
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
// default value for month: January
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
// default value for year: 1970
.parseDefaulting(ChronoField.YEAR, 1970)
// create formatter at my specific timezone
.toFormatter(Locale.ROOT).withZone(zone);
// get the millis value
long millis = Instant.from(fmt2.parse(time)).toEpochMilli();
Following changes that i've made works fine for me.
public static long convertdatetotimestamp(String datestring, String newdateformat, String olddateformat){
DateFormat originalFormat = new SimpleDateFormat(olddateformat,Locale.ENGLISH);
DateFormat targetFormat = new
SimpleDateFormat(newdateformat,Locale.ENGLISH);
Date date = null;
try {
date = originalFormat.parse(datestring.replaceAll("\\.", ""));
String formattedDate = targetFormat.format(date);
Date parsedDate = targetFormat.parse(formattedDate);
long nowMilliseconds = parsedDate.getTime();
return nowMilliseconds;
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
Locale.ENGLISH you can use your locale, english solved my issue. Reference.
Thanks for responses and references.
This code:
DateTimeParser[] parsers = { DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss zzz").getParser(),
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").getParser(), DateTimeFormat.forPattern("dd/MM/yyyy HH:mm").getParser(),
DateTimeFormat.forPattern("HH:mm").getParser() };
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
Session session;
DateTime dTime = null;
Calendar calendar;
try{
if (completedTime != null && !completedTime.equalsIgnoreCase("")){
LocalDateTime jt = LocalDateTime.parse(completedTime, formatter);
LocalDateTime dt;
LocalDateTime retDate;
produces the error:
java.lang.IllegalArgumentException: Invalid format: "09/05/2015 04:00:00 GDT" is malformed at " GDT"
at the LocalDateTime jt = LocalDateTime.parse(completedTime, formatter); line
I can't for the life of me work out why it is failing. I am pretty sure it is something simple, but I haven't spotted it.
You may want to refer to this thread (or one of the many others like it). My best advice would be to try cutting to only one "z" in your parser.
You need to manually specify a mapping from timezone abbreviation to timezone. For example:
return new DateTimeFormatterBuilder()
.appendPattern("dd/MM/yyyy HH:mm:ss ")
.appendTimeZoneShortName(UK_TIMEZONE_SYMBOLS)
.toFormatter();
Here UK_TIMEZONE_SYMBOLS is a Map<String,DateTimeZone> which contains our view of timezone names (so BST is British summer time, not Bangladesh standard time)
Here's how we build ours:
public static Map<String, String> buildTimeZoneSymbolMap(Locale locale) {
Map<String, String> timeZoneSymbols = Maps.newLinkedHashMap();
for (String[] zoneInfo : DateFormatSymbols.getInstance(locale).getZoneStrings()) {
String timeZone = zoneInfo[0];
if (!timeZoneSymbols.containsKey(zoneInfo[2])) {
timeZoneSymbols.put(zoneInfo[2], timeZone);
}
if (zoneInfo[4] != null && !timeZoneSymbols.containsKey(zoneInfo[4])) {
timeZoneSymbols.put(zoneInfo[4], timeZone);
}
}
timeZoneSymbols.put("UTC", "GMT");
return timeZoneSymbols;
}
public static Map<String, DateTimeZone> buildDateTimeZoneSymbolMap(Locale locale) {
return Maps.transformValues(buildTimeZoneSymbolMap(locale), input -> DateTimeZone.forTimeZone(TimeZone.getTimeZone(input)));
}
public static final Map<String, DateTimeZone> UK_TIMEZONE_SYMBOLS = ImmutableMap.copyOf(buildDateTimeZoneSymbolMap(Locale.UK));
First thing to note:
What is "GDT"? The website http://www.timeanddate.com/time/zones/ does not yield an answer. So if it really exists and is not a typo then what is your locale? Remember that time zone names and abbreviations are highly localized.
Second: The count of pattern symbols "z" is okay - for classes like SimpleDateFormat etc. - see its documentation. Either four letters for the full name or less than four letters for the abbreviation:
General time zone: Time zones are interpreted as text if they have
names. Text: For formatting, if the number of pattern letters is 4 or
more, the full form is used; otherwise a short or abbreviated form is
used if available. For parsing, both forms are accepted, independent
of the number of pattern letters.
But you use Joda-Time. Its documentation clearly states:
Zone names: Time zone names ('z') cannot be parsed.
I have verified this non-support using the newest Joda-Time version 2.7 by following code:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss z").withLocale(Locale.GERMANY);
DateTime dt = formatter.parseDateTime("09/05/2015 04:00:00 MESZ");
System.out.println("Joda-Time: " + dt);
// Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "09/05/2015 04:00:00 MESZ" is malformed at "MESZ"
Of course, "MESZ" is correct and must be interpreted as Europe/Berlin in context of given german locale.
However, since version update (2.2) the same code set to Locale.US works for some timezones names like "EDT", "PST" etc., see also this commit. So we can finally say, the parsing support of Joda-Time for timezone names and abbreviations is best to say very limited. Once again, what is your Locale? If it is not US then I can understand why you get the exception. And you will also get an exception for the input "GDT" even if we consider it as valid due to the limited capabilities of Joda-Time-parser.