0

I'm wondering if it's possible at all to parse a string to a LocalDate object including a formatter such as "d/M/YYYY" (specifically including the "YYYY").

It seems a JsJodaException is thrown in the console when attempting to parse this, however when formatting from a JS-Joda Temporal object to a string using the same format, it works just fine?

I understand I can use "yyyy" in place of "YYYY" - but with business constraints, I cannot do this.

The console error I get has the message of the following (an example): "Text '10/3/2023' could not be parsed"

I tried using LocalDate.parse("10/3/2023", DateTimeFormatter.ofPattern("d/M/YYYY").withLocale(Locale.ENGLISH));

However this doesn't seem to work.

Jack A
  • 11
  • 1
  • Why not just replace uppercase Y with lowercase y in the format string? – NineBerry Mar 10 '23 at 06:09
  • Hi, I can't replace with lower case at the moment because of business constraints within the scope of the task. – Jack A Mar 14 '23 at 01:31
  • Can you explain these constraints? – NineBerry Mar 14 '23 at 01:34
  • Mainly imbedded unit tests already leveraging the YYYY token - we can't easily change it and they want to use YYYY. However those unit tests are only for formatting not parsing. – Jack A Mar 14 '23 at 01:37
  • That's what I meant: In the function that does the parsing, replace uppercase Y with lowercase Y in the format string that is passed to the function. – NineBerry Mar 14 '23 at 14:41

1 Answers1

0

In the function that does the parsing, replace uppercase Y with lowercase Y in the format string that is passed to the function

function parseDate(dateString, formatString) {
   // replace Y with y in the formatString
   const adaptedFormatString = formatString.replaceAll('Y', 'y');
   
   // Use adapted formatString
   return JSJoda.LocalDate.parse(dateString, JSJoda.DateTimeFormatter.ofPattern(adaptedFormatString));
}

const d = parseDate("10/3/2023", "d/M/YYYY");
console.log(d);
<script src="https://cdn.jsdelivr.net/npm/@js-joda/core@1.11.0/dist/js-joda.js"></script>
NineBerry
  • 26,306
  • 3
  • 62
  • 93