Path: csiph.com!news.mixmin.net!newsfeed.fsmpi.rwth-aachen.de!newsfeed.straub-nv.de!news-1.dfn.de!news.dfn.de!cache.uni-koblenz.de!not-for-mail From: Tassilo Horn Newsgroups: comp.lang.java.programmer Subject: Parsing calendar weeks to LocalDates with DateTimeFormatter Date: Wed, 07 Sep 2016 08:58:48 +0200 Organization: University Koblenz-Landau Campus Koblenz Lines: 47 Message-ID: <87inu8gpqv.fsf@gnu.org> NNTP-Posting-Host: j289989.servers.jiffybox.net Mime-Version: 1.0 Content-Type: text/plain X-Trace: cache.uni-koblenz.de 1473231528 28563 134.119.24.195 (7 Sep 2016 06:58:48 GMT) X-Complaints-To: news@cache.uni-koblenz.de NNTP-Posting-Date: Wed, 7 Sep 2016 06:58:48 +0000 (UTC) User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/25.1.50 (gnu/linux) Cancel-Lock: sha1:LQrMr0EKTH2aaSloaD90GcjpsHw= Xref: csiph.com comp.lang.java.programmer:35560 Hi all, I have a DateTimeFormatter FORMATTER_KW = DateTimeFormatter.ofPattern("ww.YYYY"); for formatting LocalDates as calendar weeks. That works fine, however I can't use that to parse calendar week strings to LocalDates, e.g., FORMATTER_KW.parse("44.2016", LocalDate::from); throws java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {WeekBasedYear[WeekFields[MONDAY,4]]=2016, WeekOfWeekBasedYear[WeekFields[MONDAY,4]]=50},ISO of type java.time.format.Parsed at java.time.LocalDate.from(LocalDate.java:368) at java.time.format.Parsed.query(Parsed.java:226) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ... 63 more Sounds like it is complaining that the date is underspecified which it obviously is. So I'd like such a calendar week to resolve to the last work day in that week. (The calendar weeks are estimated deliveries.) After a bit of doc reading and experimenting, I came up with this solution which seems to work ok but looks a bit complicated for such a common task such as week-date conversion. So is there anything better? // When parsing calendar weeks like "22.2016", we want to get the last work day in that week. We // assume that everyone in every locale has a 5 days work week (don't know how to do better). return FORMATTER_KW.parse(editorText, temporal -> { WeekFields weekFields = WeekFields.of(Locale.getDefault()); DayOfWeek firstDayInWeek = weekFields.getFirstDayOfWeek(); DayOfWeek lastWorkDay = firstDayInWeek.minus(4); long weekOfWeekBasedYear = temporal.getLong(weekFields.weekOfWeekBasedYear()); long year = temporal.getLong(weekFields.weekBasedYear()); LocalDate date = LocalDate.of(0, 1, 1); date = date.plusYears(year); date = date.plusWeeks(weekOfWeekBasedYear); date = date.with(lastWorkDay); return date; }); Bye, Tassilo