I need to convert a string into a Joda DateTime object, but the code I am using is not doing the conversion correct. My input is 20140722101846-0700, which should convert to something not unlike 2014-07-22T10:18:46-0700. Here is my code, followed by the incorrect output:
String myet = "20140722101846-0700"
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMddhhmmss-hhmm");
DateTime mydt = dtf.parseDateTime(myet);
The resulting (incorrect) output is: 2014-07-22T07:00:46.000-07:00
How can I fix the code above so that is outputs a correct date?
Your DateTimeFormat doesn't have the correct symbols.
M is for month
m is for minutes
Z is used for the time zone offset (-0700)
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMddhhmmssZ");
Related
I'm trying to parse a date with the format "" to Date.
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = sdf.parse(dateStr);
String = sdf.format(date);
An example of the dateStr is "2020-04-14 16:34:40.0117372".
I get an error when trying to parse the string, but I don't know why.
The error I'm getting is the following:
java.text.ParseException: Unparseable date: "2020-04-14 16:34:40.0117372"
Why can't I parse this date? How can I do it?
You are using "dd/MM/yyyy" for date format, but you should be using "yyyy-MM-dd" (inverse order, and dashes instead of slashes)
Also I suggest you use modern java.time packages and do something like this:
String str = "2020-04-14 16:34:40.0117372";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
Edit: Having 7 digits for milliseconds is correct, first digits for milliseconds and the rest for nanoseconds. strange. Usually you want 3 digits because 1000 milliseconds is a second. You likely have nanoseconds, which should be dealt with by this method.
I´m trying to pase the next String using LocalDateTime, but I always get de unparsed text found error:
java.time.format.DateTimeParseException: Text '2020-10-16T18:04:59+0300' could not be parsed at index 24
Need: from 2020-10-16T18:04:59+0300 to 2020-10-16 18:04.
My code:
public String getFormattingData(String sourceData) {
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ''e", Locale.ENGLISH);
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy HH:mm", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2020-10-16T18:04:59+0300", sourceFormatter);
return newFormatter.format(date);
}
What am I doing wrong?
See the related question: Format a date using the new date time API
The source format you are looking for is: "yyyy-MM-dd'T'HH:mm:ssZ" (as mentioned by #Sweeper in his comment)
If you want the HH:mm in the output format, you need to use a LocalDateTime rather than a LocalDate
The code below works for me:
public String getFormattingData(String sourceData) {
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH);
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm", Locale.ENGLISH);
LocalDateTime date = LocalDateTime.parse("2020-10-16T18:04:59+0300", sourceFormatter);
return newFormatter.format(date);
result:
16-10-2020 18:04
You just need to correct the date pattern of source date like this:
public static String formatDate(String strDate, String srcPattern, String tgtPattern) {
DateTimeFormatter srcFormatter = DateTimeFormatter.ofPattern(srcPattern, Locale.ENGLISH);
DateTimeFormatter tgtFormatter = DateTimeFormatter.ofPattern(tgtPattern, Locale.ENGLISH);
return tgtFormatter.format(LocalDateTime.parse(strDate, srcFormatter));
}
You can also use SimpleDateFormat:
public static String formatDate(String strDate, String srcPattern,
String tgtPattern) throws ParseException {
SimpleDateFormat srcFormatter = new SimpleDateFormat(srcPattern, Locale.ENGLISH);
SimpleDateFormat tgtFormatter = new SimpleDateFormat(tgtPattern, Locale.ENGLISH);
return tgtFormatter.format(srcFormatter.parse(strDate));
}
And then call it with any pattern that you want:
System.out.println(formatDate("2020-10-16T18:04:59+0300", "yyyy-MM-dd'T'HH:mm:ssZ", "dd-MM-yyy HH:mm"));
Don’t write a method that converts a date and time from a string in one format to a string in a different format. In your program keep dates and times as proper date-time objects. Just like you don’t keep numbers and Boolean values in strings (I hope!) When you receive string input, parse into a date-time object at once. Only when you need to give string output, format into an appropriate string.
When I receive a string containing date, time and UTC offset, like yours does, I prefer to parse it into a OffsetDateTime so I get all the information. It’s easier to throw unneeded information away later than to invent the information that we neglected to parse. Also a LocalDate will not work for your purpose since it doesn’t contain time of day. So you cannot format one into 2020-10-16 18:04 format.
For parsing your string I would use:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendOffset("+HHmm", "Z")
.toFormatter();
String sourceData = "2020-10-16T18:04:59+0300";
OffsetDateTime dateTime = OffsetDateTime.parse(sourceData, formatter);
System.out.println(dateTime);
Output is:
2020-10-16T18:04:59+03:00
The definition of the formatter is longish but has the advantage of reusing predefined formatters for date and time.
For displaying a formatted date and time to the user, don’t you want to use the user’s time zone rather then the offset that happened to be in the string (+03:00 in your case)?
ZoneId zone = ZoneId.of("Antarctica/South_Pole");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm", Locale.ENGLISH);
String formatted = dateTime.atZoneSameInstant(zone).format(newFormatter);
System.out.println(formatted);
17-10-2020 04:04
What went wrong in your code?
As others have said, yyyy-MM-dd'T'HH:mm:ssZ in your format pattern string for parsing parses your entire date-time string of 2020-10-16T18:04:59+0300 nicely. The ''e at the end of the format pattern is the culprit. This would require an additional single quote (apostrophe) and the number of the day of the week to be present (pattern letter e is for localized day of week). Since Java had successfully parsed 24 chars and then failed to parse an apostrophe, it threw the exception mentioning thst the string could not be parsed at index 24.
I need to convert a String containing a date into a date object.
The String will be in the format "yyyy-mm-dd HH:mm:ss" and I want the "MM/dd/yyyy HH:mm:ss a " format as result.
String dateString = "2018-03-20 09:31:31";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a",
Locale.ENGLISH);
LocalDate date = LocalDate.parse(dateString , formatter);
The code above is throwing an exception.
You have to use two Formatter, one to covert String to LocalDateTime and the other to format this date as you want :
From String to LocalDateTime :
String dateString = "2018-03-20 09:31:31";
LocalDateTime date = LocalDateTime.parse(
dateString,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
);
Now From LocalDateTime to String :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy HH:mm:ss a", Locale.ENGLISH
);
String newDate = date.format(formatter);
System.out.println(newDate);// 03/20/2018 09:31:31 AM
Note : You have to use LocalDateTime instead of just LocalDate, your format contain both date and time, not just date, else you will get an error :
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
That's a common error, based on the misconception that dates have formats - but they actually don't.
Date/time objects have only values, and those values - usually numerical - represent the concept of a date (a specific point in the calendar) and a time (a specific moment of the day).
If you have a String, then you don't actually have a date. You have a text (a sequence of characters) that represents a date. Note that all of the strings below are different (they have a different sequence of characters), but all represent the same date (the same values, the same point in the calendar):
2018-03-20 09:31:31
03/20/2018 9:31:31 AM (using USA's format: month/day/year)
Tuesday, March 20th 2018, 09:31:31 am
and many others...
What you want to do is to get one format (one String, one text representing a date) and transform it to another format (anoter String, another different sequence of characters that represents the same date).
In Java (and in many other languages - if not all - btw) you must do it in 2 steps:
convert the String to a date/time object (convert the text to the numerical values) - that's what the parse method does
convert the date/time object to another format (convert the numerical values to another text)
That said, when you call the parse method, you're trying to transform a String (a text, a sequence of characters) into a date/time object. This means that the DateTimeFormatter must have a pattern that matches the input.
The input is 2018-03-20 09:31:31, which is year-month-day hour:minute:second. And the formatter you used to parse it has the pattern MM/dd/yyyy HH:mm:ss a (month/day/year hour:minute:second am/pm).
You used the output pattern (the one that should be used in step 2) to parse the input. That's why you've got an exception: the formatter tried to parse a month with 2 digits followed by a / when the input actually contains a year with 4 digits followed by a -.
You must use a different DateTimeFormatter for each step, using the correct pattern for each case. YCF_L's answer has the code that does the job, I'd just like to add one little detail. The formatter used for the output (step 2) is:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy HH:mm:ss a", Locale.ENGLISH
);
Note that HH is used for the hours. Take a look at the javadoc and you'll see that uppercase HH represents the hour-of-day fields (values from 0 to 23 - so 1 AM is printed as 01 and 1 PM is printed as 13).
But you're also printing the AM/PM field (the a in the pattern), so maybe what you need is actually the lowercase hh, which is the clock-hour-of-am-pm (values from 1 to 12) or even KK (hour-of-am-pm (values from 0 to 11)).
String dateString = "2018-03-20 09:31:31";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = formatter.parse(dateInString);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String reportDate = df.format(date );
} catch (ParseException e) {
e.printStackTrace();
}
You need to do a 2 steps conversion:
from your String date time in the wrong format to a (tempoary) LocalDateTime object.
if you still want to only extract the date (Year-Month-day) do a LocalDateTime.toLocalDate()
From this LocalDateTime object into the your String object in the right format
String dateString = "2018-03-20 09:31:31";
DateTimeFormatter formatterForWrongFormat = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(" ")
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();
//1- from String(wrong format) into datetime object
LocalDateTime dateTime = LocalDateTime.parse(dateString , formatterForWrongFormat);
// 1.1 extract date object (Optional)
LocalDate myDate = dateTime.toLocalDate();
// 2- now from your LocalDateTime to the String in the RIGHT format
DateTimeFormatter formatterForRightFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a",
Locale.ENGLISH);
System.out.println("right format: "+dateTime.format(formatterForRightFormat));
you can test this code here
You can use the SimpleDateFormatter which is easier to implement and permit you to change the format of your date easily.
More here : What are the date formats available in SimpleDateFormat class?
Hope this will help you !
I have this time. 8:32:00 PM. How do I convert this to a 24hr Joda-Time LocalTime format? There's no time converter in the Joda-Time library
Start by parsing the String to a LocalTime...
String timeValue = "8:32:00 PM";
DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("h:mm:ss a").toFormatter();
LocalTime localTime = LocalTime.parse(timeValue, parseFormat);
Then format the result...
DateTimeFormatter outputFormat = new DateTimeFormatterBuilder().appendPattern("H:mm:ss").toFormatter();
String formatted = localTime.toString(outputFormat);
System.out.println(formatted);
Which will output 20:32:00
Remember, the value of LocalTime and the format are two separate concepts, you can't affect the "format" of the LocalTime object itself, you can only translate the concept of the value to a String representation (via a formatter)
If I understand your question,
Once I converted the time to a localtime how do I convert it to its equivalent 24hr format?
You would use DateTimeFormat to create a DateTimeFormatter, like so -
DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");
String str = fmt.print(dt);
Excerpted from the linked javadoc,
H hour of day (0~23) number 0
m minute of hour number 30
s second of minute number 55
You don't want to convert the time (they're the same time), you want to format the time. Joda has a DateTimeFormatter class (see http://www.joda.org/joda-time/key_format.html for details).
You can use it something like this:
DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm:ss");
String str = date.toString(fmt);
I need to change the SimpleDateFormat to some other format which is equivalent in jodatime.
Here's the code which needs to be changed.
public static String dateFormat(Date date, String format)
{
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
I have tried to use DateTimeFormatter.
public static String dateFormat(DateTime date, String format)
{
DateTimeFormatter dtf = DateTimeFormat.forPattern(format);
DateTime tempDateTime = dtf.parseDateTime(date.toString());
return tempDateTime.toString();
}
But I am getting Error.
Well, I look for you in the documentation of Joda Time and SimpleDateFormat. As you can see there, the pattern definitions are unfortunately not the same. If you translate from SimpleDateFormat to Joda-DateTimeFormat, then you have to note following items:
Change Y to x (so called week-year).
Change y to Y (year-of-era) and maybe changing the chronology, too (from ISO to Gregorian/Julian)
W is not supported in Joda Time (week of month), hence no replacement!
F is not supported in Joda Time (day of week in month), hence no replacement!
Change u to e (day number of week - ISO order, not localized), available since Java 7.
The symbol S is handled differently (I suppose in Joda Time better because of correct zero padding).
The zone symbol z is in Joda Time not allowed for parsing (maybe this is the current cause of your problems - you have not shown your pattern format or your exception yet).
The zone/offset symbol Z is handled better in Joda Time, for example allows colons in offset etc. If you need latter you can use X in SimpleDateFormat which has the replacement Z in Joda Time.
Some tests added:
Following sample code demonstrates the different handling of format symbol S.
String s = "2014-01-15T14:23:50.026";
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSS");
DateTime instant = dtf.parseDateTime(s);
System.out.println(dtf.print(instant)); // 2014-01-15T14:23:50.0260
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS");
Date date = sdf.parse(s);
System.out.println(sdf.format(date)); // 2014-01-15T14:23:50.0026 (bad!)
Another test for format symbol z (is that your problem???):
String s = "2014-01-15T14:23:50.026PST";
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz");
DateTime instant = dtf.parseDateTime(s);
System.out.println(dtf.print(instant)); // abort
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2014-01-15T14:23:50.026PST" is malformed at "PST"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:866)
at time.JodaTest8.main(JodaTest8.java:83)
SimpleDateFormat can do this zone name parsing (although at least dangerous sometimes):
String s = "2014-01-15T14:23:50.026PST";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
Date date = sdf.parse(s);
System.out.println(sdf.format(date)); // 2014-01-15T14:23:50.026PST