Parse a String with week and year into a LocalDate [duplicate] - java

This question already has answers here:
How to parse date from string with year and week using java.time
(3 answers)
Closed 3 years ago.
The kind of String I want to parse : "36/2017", with 36 the week of the year, 2017 the year.
My code :
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("w/uuuu")
.parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
.toFormatter();
LocalDate date = LocalDate.parse("36/2017", formatter);
I added a default day.
I have this message :
java.time.format.DateTimeParseException: Text '36/2017' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {WeekOfWeekBasedYear[WeekFields[MONDAY,4]]=36, Year=2017, DayOfWeek=1},ISO of type java.time.format.Parsed
Any idea ?
Thank you !

From the docs: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
You should use uppercase Y's if you are using weeks.
public static void main(String[] args) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("w/YYYY")
.parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
.toFormatter();
LocalDate date = LocalDate.parse("36/2017", formatter);
}

The pattern is wrong. You must set the following string
"w/YYYY"
DateTimeFormatter formatter = new
DateTimeFormatterBuilder()
.appendPattern("w/YYYY")
.parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
.toFormatter();
LocalDate date = LocalDate.parse("36/2017", formatter);

Related

Convert string to LocalDateTime or OffsetDateTime [duplicate]

This question already has answers here:
Can't parse String to LocalDate (Java 8)
(2 answers)
Difference between year-of-era and week-based-year?
(7 answers)
Closed 2 years ago.
I have the following code:
String dateTimeInStr = "17-Jul-2020 12:12";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-YYYY HH:mm");
// OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateTimeInStr, formatter);
LocalDateTime localDateTime = LocalDateTime.parse(dateTimeInStr, formatter);
System.out.println(localDateTime);
// System.out.println(offsetDateTime);
As you can see I try convert string 17-Jul-2020 12:12 to the LocalDateTime or OffsetDateTime. But nothing works.
Text '17-Jul-2020 12:12' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {WeekBasedYear[WeekFields[MONDAY,1]]=2020, MonthOfYear=7, DayOfMonth=17},ISO resolved to 12:12 of type java.time.format.Parsed
Does anyone know how to fix this issue? Thanks in advance.
Case-sensitive
You are using uppercase 'YYYY' which is the week year. Try with lowercase 'yyyy':
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm");
Locale
And specify a Locale for the human language and cultural norms used in translating the name of month.
DateTimeFormatter formatter =
DateTimeFormatter
.ofPattern("dd-MMM-yyyy HH:mm")
.withLocale( Locale.US );
See this code run live at IdeOne.com.
2020-07-17T12:12

Java - Parse date with optional seconds [duplicate]

This question already has answers here:
How do I simply parse a date without a year specified?
(5 answers)
DateTimeFormatter could not be parsed using "HH:mm E d MMM YYYY" pattern
(2 answers)
Closed 4 years ago.
Given this date I want to parse: 15th Dec 16:00 +01:00
with this code
Map<Long, String> ordinalNumbers = new HashMap<>(42);
ordinalNumbers.put(1L, "1st");
ordinalNumbers.put(2L, "2nd");
ordinalNumbers.put(3L, "3rd");
ordinalNumbers.put(21L, "21st");
ordinalNumbers.put(22L, "22nd");
ordinalNumbers.put(23L, "23rd");
ordinalNumbers.put(31L, "31st");
for (long d = 1; d <= 31; d++) {
ordinalNumbers.putIfAbsent(d, "" + d + "th");
}
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.DAY_OF_MONTH, ordinalNumbers)
.appendPattern(" MMM HH:mm[:ss] xxx")
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter().withLocale(Locale.ENGLISH);
ZonedDateTime eventDate = ZonedDateTime.parse("15th Dec 16:00 +01:00", formatter);
but I always get
java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {DayOfMonth=15, MonthOfYear=12, OffsetSeconds=3600},ISO resolved to 16:00 of type java.time.format.Parsed
You can try it out online here: https://repl.it/repls/NaiveRegularEquation
Please tell me what I do wrong.
UPDATE:
The missing year was the problem.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.DAY_OF_MONTH, ordinalNumbers)
.appendPattern(" MMM HH:mm[:ss] xxx")
.parseDefaulting(ChronoField.YEAR, 2018)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter().withLocale(Locale.ENGLISH);
Specify year
ZonedDateTime needs a year field, while you did not provide it.
You can set a default value:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseDefaulting(ChronoField.YEAR_OF_ERA, ZonedDateTime.now().getYear()) // set default year
.appendText(ChronoField.DAY_OF_MONTH, ordinalNumbers)
.appendPattern(" MMM HH:mm[:ss] xxx")
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter().withLocale(Locale.ENGLISH);

Month Year In String to Date Java 8 [duplicate]

This question already has answers here:
How to convert date from MM/YYYY to MM/DD/YYYY in Java
(4 answers)
Closed 4 years ago.
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/yyyy");
LocalDate parsedDate = LocalDate.parse(entryOne.getKey(), dateFormat)
Getting exception
Text '03/2018' could not be parsed: Unable to obtain LocalDate from TemporalAccessor:
How to parse this string and convert to Date using Java 8 having default first day of the month. Something what we do using.
TemporalAdjusters.firstDayOfMonth()
You have two choices for converting a MM/yyyy string into a LocalDate:
Parse as YearMonth then convert to LocalDate:
String date = "04/2018";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/yyyy");
YearMonth yearMonth = YearMonth.parse(date, dateFormat);
LocalDate parsedDate = yearMonth.atDay(1);
System.out.println(parsedDate); // prints: 2018-04-01
Use a DateTimeFormatter with a default day-of-month defined:
String date = "04/2018";
DateTimeFormatter dateFormat = new DateTimeFormatterBuilder()
.appendPattern("MM/yyyy")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter();
LocalDate parsedDate = LocalDate.parse(date, dateFormat);
System.out.println(parsedDate); // prints: 2018-04-01
Here's what works for me:
String dateAsString = "03/2018";
DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/yyyy");
DateTime dt = fmt.parseDateTime(dateAsString);
LocalDateTime ldt = new LocalDateTime(dt);
int dayOfWeek = ldt.getDayOfWeek(); //has value of 4 since Thursday was the first day of March

convert shortdate to LocalDate

Hi i have a short date format with me in the pattern E dd/MM , Is there any way i can convert it to LocalDate.
String date = "Thu 07/05";
String formatter = "E dd/MM";
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
final LocalDate localDate = LocalDate.parse(date, formatter);`
But it throws an exception java.time.format.DateTimeParseException: Text 'Thu 07/05' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=5, DayOfMonth=7, DayOfWeek=4},ISO of type java.time.format.Parsed
Is there any way we can fix this issue ?
All you have is a month and a day - so you can create a MonthDay (to create a LocalDate you would also need a year):
MonthDay md = MonthDay.parse(date, formatter);
If you want a LocalDate, you can use the MonthDay as a starting point:
int year = Year.now().getValue();
LocalDate localDate = md.atYear(year);
Or alternatively you can use a default year in your formatter:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern(pattern)
.parseDefaulting(ChronoField.YEAR, year)
.toFormatter(Locale.US);
LocalDate localDate = LocalDate.parse(date, formatter);
The benefit of this method is that it will also check that the day of week (Thursday) is correct.

Why my pattern("yyyyMM") cannot parse with DateTimeFormatter (java 8)

When I using SimpleDateFormat, it can parse.
SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
format.setLenient(false);
Date d = format.parse(date);
But When I use Java 8 DateTimeFormatter,
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
LocalDate localDate = LocalDate.parse(date, formatter);
it throws
java.time.format.DateTimeParseException: Text '201510' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2015, MonthOfYear=10},ISO of type java
.time.format.Parsed
String value for date is "201510".
Ask yourself the question: which day should be parsed with the String "201510"? A LocalDate needs a day but since there is no day in the date to parse, an instance of LocalDate can't be constructed.
If you just want to parse a year and a month, you can use the YearMonth object instead:
YearMonth localDate = YearMonth.parse(date, formatter);
However, if you really want to have a LocalDate to be parsed from this String, you can build your own DateTimeFormatter so that it uses the first day of the month as default value:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("yyyyMM")
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter();
LocalDate localDate = LocalDate.parse(date, formatter);
You can use a YearMonth and specify the day you want (say the first for example):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
LocalDate localDate = YearMonth.parse(date, formatter).atDay(1);
Or if the day is irrelevant, just use a YearMonth.

Categories