The date I fetched from an open API is 2021-04-28. I want to format it in this way: 4/28/2021. Below is the method I tried:
public String formatDateFetchedFromAPI(String transDate) {
LocalDate apiDate = LocalDate.parse(transDate, DateTimeFormatter.BASIC_ISO_DATE);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
String actualDate = formatter.format(apiDate);
return actualDate;
}
This throws an error saying:
java.time.format.DateTimeParseException: Text '2021-04-28' could not be parsed at index 4
If the data that I pull from open API is 20210426 then this method works just fine and returns 4/28/2021.
Your date looks like an ISO_LOCAL_DATE and not BASIC_ISO_DATE, so instead you can just use
LocalDate apiDate = LocalDate.parse(transDate);
without DateTimeFormatter, because LocalDate.parse by default uses ISO_LOCAL_DATE.
Related
I am using the following timestamp format:
yyyyMMddHHmmssSSS
The following method works fine:
public static String formatTimestamp(final Timestamp timestamp, final String format) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
return timestamp.toLocalDateTime().format(formatter);
}
And, when I pass in a Timestamp with that format string, it returns, for example:
20170925142051591
I then require to map from that string to a Timestamp again, essentially the reverse operation. I know that I can use a SimpleDateFormat and its parse() method, but I'd prefer to stick to java.time style formatting, if possible.
I wrote this (rather hacky) bit of code, which works with some formats, but not with this particular one:
public static Timestamp getTimestamp(final String text, final String format, final boolean includeTime) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
final TemporalAccessor temporalAccessor = formatter.parse(text);
if (includeTime) {
final LocalDateTime localDateTime = LocalDateTime.from(temporalAccessor);
return DateTimeUtil.getTimestamp(localDateTime);
} else {
final LocalDate localDate = LocalDate.from(temporalAccessor);
return DateTimeUtil.getTimestamp(localDate);
}
}
It fails on the second line, at the formatter.parse(text); part.
Stack Trace:
java.time.format.DateTimeParseException: Text '20170925142051591' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at java.time.LocalDateTime.parse(LocalDateTime.java:477)
at com.csa.core.DateTimeUtil.main(DateTimeUtil.java:169)
Is there a simpler way to achieve what I want without utilising SimpleDateFormat?
It's a bug: https://bugs.openjdk.java.net/browse/JDK-8031085
The link above also provides the workaround: using a java.time.format.DateTimeFormatterBuilder with a java.time.temporal.ChronoField for the milliseconds field:
String text = "20170925142051591";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
// date/time
.appendPattern("yyyyMMddHHmmss")
// milliseconds
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
// create formatter
.toFormatter();
// now it works
formatter.parse(text);
Unfortunately, there seems to be no way to parse this using only DateTimeFormatter.ofPattern(String).
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"
I have string in this format "2015-11-18T00:00:00+0000". I thought it's a ISO8601 format and tried to parse it to a Joda DateTime instance, but it told me it's malformed:
String toParse = "2015-11-18T00:00:00+0000";
DateTime date = ISODateTimeFormat.dateTime().parseDateTime(toParse);
And I got this error:
java.lang.IllegalArgumentException: Invalid format: "2015-11-18T00:00:00+0000" is malformed at "+0000"
How can I convert the above string to a DateTime?
The method ISODateTimeFormat.dateTime() requires a millisecond part which is missing in your input. Solution: Use the method dateTimeNoMillis().
String input = "2015-11-18T00:00:00+0000";
DateTime dt = ISODateTimeFormat.dateTimeNoMillis().parseDateTime(input);
System.out.println(dt); // 2015-11-18T01:00:00.000+01:00 (using offset of default timezone)
If you want to preserve the offset (+0000) contained in your input then you will also need to call withOffsetParsed() on your formatter.
I have following code:
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM");
LocalDate weekMon = new LocalDate().withWeekOfWeekyear(thisWeek).withDayOfWeek(DateTimeConstants.MONDAY);
System.out.println(weekMon.toString());
LocalDate weekFin = dtf.parseLocalDate(weekMon.toString());
and the output prints the date correctly: 2015-02-02. I'm trying to convert it to European format and ignoring the year as "dd-MM" -> "02-02" but the line:
LocalDate weekFin = dtf.parseLocalDate(weekMon.toString());
keeps throwing following exception:
java.lang.IllegalArgumentException: Invalid format: "2015-02-02" is malformed at "5-02-02"
What is wrong with the formation in this case ?.
Probably what you need is to print, and not to parse.
In other words:
String dateStr = dtf.print(weekMon);
Notice that with this code:
LocalDate weekFin = dtf.parseLocalDate(weekMon.toString());
you are trying to parse a string in "yyyy-MM-dd" format using a formatter that accepts strings in "dd/MM" format. Hence the exception...
I'm new in OFBiz, and Java. I used bellow block of code for checking date time input and use that for searching in table.
Timestamp strtDate = UtilDateTime.getTimestamp((String)request.getParameter("strt_date"));
if(strtDate != null)
{
// then here i used the date for taking data.
}
When i fill the date time field of form to search or when no date is selected for searching error occure that show numberFormatException, so how i can solve that? thanks for any help and guide.
Based on the Apache ofbiz API it looks like UtilDateTime#getTimestamp(String) expects milliseconds value. You are passing in "2014-01-12 05-44-56". You need to parse your date first. With pure pre 1.8 java (keep in mind that formatters aren't thread safe):
String dateString = "2014-01-12 05-44-56";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
Date date = formatter.parse(dateString);
UtilDateTime.getTimestamp(date.getTime());
Since java 1.8 (highly recommended to switch if you can!):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
ZonedDateTime date = ZonedDateTime.parse(text, formatter);
long millis = date.toInstant().toEpochMilli();
you have to pass time in milliseconds not as you are passing.
you can check code also :
public static Timestamp getTimestamp(String milliSecs) throws NumberFormatException {
return new Timestamp(Long.parseLong(milliSecs));
}
it will parse the data in long which you are passing and that should be valid long value.
request.getParameter("strt_date") will anyways return String, so no need to cast it explicitly to String. Moreover, there will be a contract between Client & Server on the required Date Format. So you have to parse the String-Date in the same format using SimpleDateFormat. Code outlook will look like bellow:
SimpleDateFormat formatter = new SimpleDateFormat("contract-date-format");
Date date = formatter.parse(request.getParameter("strt_date"));
UtilDateTime.getTimestamp(date.getTime());