Cannot parse threeten datetime to a specific format [duplicate] - java

This question already has answers here:
Can’t rid of 'T' in LocalDateTime
(3 answers)
How to prevent auto-generated 'T' letter when parsing String to LocalDateTime using DateTimeFormatterBuilder [duplicate]
(1 answer)
Closed 2 years ago.
I'm trying to format Threeten datetime, from yyyy-MM-dd'T'HH:mm:ss to yyyy-MM-dd HH:mm:ss. Below is the code, I'm using to achieve the task.
public void testChangeFormat() {
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date1 = LocalDateTime.parse("2020-03-10T15:14:05", inputFormatter);
System.out.println(date1); // prints 2020-03-10T15:14:05
String formattedDate = outputFormatter.format(date1);
System.out.println(formattedDate); // prints 2020-03-10 15:14:05
LocalDateTime newFormattedDateTime = LocalDateTime.parse(formattedDate);
System.out.println(newFormattedDateTime);
}
Everything seems to work as expected until I try to parse the formattedDate to LocalDateTime, at LocalDateTime newFormattedDateTime = LocalDateTime.parse(formattedDate);
I even get the datetime formatted as 2020-03-10 15:14:05 using outputFormatter, but when I try to parse that to LocalDateTime, it gives me the following exception:
org.threeten.bp.format.DateTimeParseException: Text '2020-03-10 15:14:05' could not be parsed at index 10
Can somebody help me with this?

LocalDateTime.parse(formattedDate) are using DateTimeFormatter.ISO_LOCAL_DATE_TIME (that is format yyyy-MM-dd'T'HH:mm:ss). That's why you get the exception when trying to parse string that has format yyyy-MM-dd HH:mm:ss. You should use:
LocalDateTime.parse(formattedDate, outputFormatter) if you wnat to do the parse to LocalDateTime again for some reason.
Note:
You have the printed format you at line: outputFormatter.format(date1) right?

You seem to be confused between LocalDateTime and format (which is a string representation).
A LocalDateTime always has T in it when you print its object using System.out.println (which implicitly calls toString as you most likely already know) e.g.
System.out.println(LocalDateTime.now());
will output 2020-04-14T09:36:04.723994.
See below how the toString of LocalDateTime has been implemented:
#Override
public String toString() {
return date.toString() + 'T' + time.toString();
}
and therefore your following statement will always show 'T' in it:
System.out.println(newFormattedDateTime);
It's up to you to format a LocalDateTime into the String representation of your choice. As I have mentioned in the first line, formats are strings i.e. you format a LocalDateTime into a String representation where you can apply all the options provided by DateTimeFormatter.
The correct way of converting the formattedDate to LocalDateTime is by applying the corresponding format which is specified in outputFormatter.
LocalDateTime newFormattedDateTime = LocalDateTime.parse(formattedDate,outputFormatter);
How date and time are stored in a LocalDateTime object shouldn't be a concern. We can always create the string in the required format from it.

Related

How to change LocalDate format resulting into a LocalDate without resulting into a String [duplicate]

This question already has answers here:
How to format LocalDate object to MM/dd/yyyy and have format persist
(4 answers)
How can you make LocalDate to return Date in a specific format?
(1 answer)
Closed 2 years ago.
In a need to convert Java LocalDate of the format of dd-MM-yyyy into a LocalDate of dd/MM/yyyy.
Trying with :
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate date = // LocalDate value in dd-MM-yyyy format
String stringDate = dateFormat.format(date);
LocalDate convertedDate = LocalDate.parse(stringDate, dateFormat);
But still it resulting into return a date in dd-MM-yyyy format. Any efficient way to do this?
The default toString implementation in LocalDate.java seems to be hardwired with '-' as a separator. So all default print statements will result into same format. Seems only way out would be to use a formatter and get a string output.
return buf.append(monthValue < 10 ? "-0" : "-")
.append(monthValue)
.append(dayValue < 10 ? "-0" : "-")
.append(dayValue)
.toString();
Also, purpose of LocalDate.parse(..) is not to convert the date format. It's actually meant to just get a date value in String and give a resulting LocalDate instance.
Hope this helps.

Why isn’t DateTimeFormatter formatting my String?

I have a simple Date String headerValues[5]="24.11.1946". I just want to convert, parse it to a Date Object.
So I use
DateTimeFormatter formatter = ofPattern(("dd.MM.yyyy");
headerLine.setStartDate(LocalDate.parse(headerValues[5],datePattern));
Output is 2012-04-25 not my desired 24.11.1946???
Why???
EDIT
I tried this...
DateTimeFormatter datePattern = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.GERMANY);
String date = "24.11.1946";
System.out.println("Date = "+ LocalDate.parse(date,datePattern));
Output is...
Date = 1946-11-24
This part of your code...
LocalDate.parse(date,datePattern)
creates a LocalDate instance.
Hence in this line of your code...
System.out.println("Date = "+ LocalDate.parse(date,datePattern));
you are actually calling method toString() of class LocalDate.
From the javadoc of that method...
The output will be in the ISO-8601 format uuuu-MM-dd.
You don't want that format. You want the format of your datePattern object. Hence you should change the last line of the code you posted to...
System.out.println(datePattern.format(LocalDate.parse(date,datePattern)));
In other words, the same DateTimeFormatter object can be used both to parse a String to a date and to format a date to a String.

Java 8 DateTimeFormatter to ignore millisecond and zone

I am struggling with Java 8 DateTimeFormatter.
I would like to convert a given String to dateFormat and parse to LocalDateTime
Here is my code
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")
String text = "2020-01-01T01:01:11.123Z"
LocalDateTime date = LocalDateTime.parse(text, f)
But Java throws
Text could not be parsed, unparsed text found at index 19
If I change ofPattern to yyyy-MM-dd'T'HH:mm:ss.SSSX, my code executes without any error.
But I don’t want to use millisecond and time zone.
Do this instead:
String text = "2020-01-01T01:01:11.123Z";
LocalDateTime date = ZonedDateTime.parse(text)
.toLocalDateTime();
To get rid of the milliseconds information, do:
LocalDateTime date = ZonedDateTime.parse(text)
.truncatedTo(ChronoUnit.SECONDS)
.toLocalDateTime();
You can also use OffsetDateTime in place of ZonedDateTime.

Convert a string into iso date format

So I am trying to convert a string into an iso format for the date.
This is the string that I am trying to convert "2016-07-05 02:14:35.0"
I would like to have it in this format the iso 8601
"2016-07-05T02:14:35.0"
I have this so far
DateTimeFormatter format = DateTimeFormat.forPattern("YYYY-MM-DDTHH:mm:sszzz");
new LocalDate();
LocalDate newDate = LocalDate.parse(created,format);
created = newDate.toString();
But it is giving me this exception
ERROR: Illegal pattern component: T; nested exception is java.lang.IllegalArgumentException: Illegal pattern component: T
I followed the examples and I don't know what I am doing wrong here.
Any help would be appreciated.
Firstly, that value is a LocalDateTime, not a LocalDate. If you want to get a date out in the end, I'd convert it to a LocalDateTime first, then take the date part of that.
When performing date formatting and parsing, always read the documentation really carefully. It looks like you're using Joda Time (due to using forPattern; if you can move to Java 8 that would be beneficial). That means you should be reading the DateTimeFormat docs.
Current problems with your pattern:
You're using 'D' instead of 'd'; that means day-of-year
You've specified 'T' without quoting it, and it isn't in the pattern anyway
You've ignored the fraction-of-second part of your value
You've specified 'zz' when there's no time zone indicator in the value.
Here's a working example:
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
String text = "2016-07-05 02:14:35.0";
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.S");
LocalDateTime localDateTime = LocalDateTime.parse(text, format);
System.out.println(localDateTime);
}
}
If you actually want to parse values with T in the middle, you'd use a pattern of "yyyy-MM-dd'T'HH:mm:ss.S" - note how then the T is quoted so it's treated literally instead of as a format specifier.
Note that this is just parsing. It's not "converting a string into ISO date format" - it's converting a string into a LocalDateTime. If you then want to format that value in an ISO format, you need to be using DateTimeFormatter.print, with an appropriate format. For example, you might want to convert to a format of yyyy-MM-dd'T'HH:mm:ss.S':
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
String text = "2016-07-05 02:14:35.0";
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.S");
LocalDateTime localDateTime = LocalDateTime.parse(text, parser);
DateTimeFormatter printer = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.S");
String formatted = printer.print(localDateTime);
System.out.println(formatted); // Output 2016-07-05T02:14:35.0
}
}
The code above will only handle a single digit fraction-of-second. You could parse using .SSS instead of .S, but you really need to work out what you want the output to be in different cases (e.g. for 100 milliseconds, do you want .1 or .100?).
You have some errors in your code:
The pattern should be 'yyyy-MM-dd HH:mm:ss.SSS'. Be aware of upper-
and lowercase.
Use LocalDateTime to get date and time. LocalDate only holds the date.
The corrected code:
String created = "2016-07-05 02:14:35.000";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime newDate = LocalDateTime.parse(created,format);
created = newDate.toString();
System.out.println(created);
Use the following format to convert
String format = "yyyy-mm-dd hh:mm:ss"
You are using the wrong format to convert. Using T is only to separate the date from time.
Use the format like this
String = "yyyy-MM-dd'T'HH:mm:ss"

Converting date string build from date and time picker [duplicate]

This question already has answers here:
Parse String to Date with Different Format in Java
(10 answers)
Closed 1 year ago.
I have a date and time picker and I build a string date using these two. Here's a sample date and time string.
"11/6/2013 09:23"
Now I need to convert them into a date and convert them to this format "yyyy-MM-dd'T'HH:mm:ss.SSS".
My problem is I'm having this error in my logcat:
11-06 21:23:53.060: E/Error(26255): Unparseable date: "11/6/2013 09:23" (at offset 2)
I'm using this code to do the conversion of string to date, and the date to a formatted string.
Date d = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault()).parse(etaToDeliverArrivedAtShipper.getText().toString());
ETAtoNextStop = d.toString();
When I use new Date and get the current date, it works fine. I guess the format of my string is wrong. But I'm displaying it on an edittext in that format. I want to stay it in that way. Is there anyway to convert this string format to a date? Any ideas guys? Thanks!
I think you are trying to do 2 things at once. In order to convert any String to another String in a different format you need to:
Parse the string with a DateFormat containing the current format, this returns a Date; then
take your newly obtained Date and format it under the desired DateFormat
SimpleDateFormat formatOne = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = formatOne.parse(etaToDeliverArrivedAtShipper.getText().toString());
SimpleDateFormat formatTwo = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS",Locale.getDefault());
String result = formatTwo.format(date)
you are trying to parse in yyyy-MM-dd'T'HH:mm:ss.SSS but it is not. it is probably yyyy/M/dd HH:mm:ss
What you probably want is:
Date d = new SimpleDateFormat("yyyy/M/dd HH:mm:ss", Locale.getDefault()).parse(etaToDeliverArrivedAtShipper.getText().toString());
ETAtoNextStop = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault()).format(d);
This is simply because your pattern is not matching the date string you are trying to parse. There are 3 errors in your pattern :
You use MM which means the month should be on two digits, while in the date it is only 1 digit
You use .SSS which means there are milliseconds but your date is not that precise
You are using the wrong delimiter
So the right pattern should be : yyyy/M/dd HH:mm:ss
To get the desired format, then create a new SimpleDateFormat object with the desired pattern and use the parse(Date) method giving it the Date object previously returned by parse().

Categories

Resources