Home > database >  How to to check if the user inserted the date in this format week number and last two digits of the
How to to check if the user inserted the date in this format week number and last two digits of the

Time:01-22

I want to check if the user inserted the date in this format
for example: String date = "1420"; where 14 is the week number of the year and 20 is the year 2020

I have created this method but it doesnt work. What is the correct pattern? Also can you share me a link or something where i can see these patterns.

public static boolean checkDate (String date) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("wwuu");
    try {
        LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
        System.out.println("The string is a date and time: "   dateTime);
        return true;
    } catch (DateTimeParseException dtpe) {
        System.out.println("The string is not a date and time of format \"wwuu\" : "   dtpe.getMessage());
        return false;
    }
}

I get this message The string is not a date and time of format "wwuu" : Text '1420' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {WeekOfWeekBasedYear[WeekFields[SUNDAY,1]]=14, Year=2020},ISO of type java.time.format.Parsed

CodePudding user response:

Using 'u' to specify the year does not seem to work. Instead you should use 'Y'. According to the documentation, this defines the "week-based-year" ( https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html ).

But there is still a problem with the formatter. By specifying a week and a year, there is no way for the parser to know which day of the week and which time of the day should be considered when parsing a date. You can use a DateTimeFormatterBuilder to specify default values for the things that are not in the string to be formated. Here is your code adapted:

public static boolean checkDate (String date) {
    DateTimeFormatter formatter =  new DateTimeFormatterBuilder().appendPattern("wwYY")
        .parseDefaulting(WeekFields.ISO.dayOfWeek(), DayOfWeek.MONDAY.getValue())
        .toFormatter();
    try {
      LocalDateTime dateTime = LocalDate.parse(date, formatter).atStartOfDay();
      System.out.println("The string is a date and time: "   dateTime);
      return true;
    } catch (DateTimeParseException dtpe) {
      System.out.println("The string is not a date and time of format \"wwuu\" : "   dtpe.getMessage());
      return false;
    }
  }

I defined the formatter to use Monday as the default day of the week. Then I formatted just a LocalDate and specified that I want this date "atStartOfDay".

CodePudding user response:

You can try to split your date string with simple RegEx date1.split("-") and parse them to integer number with Integer.parseInt("dd"),Integer.parseInt("mm") and so on. Then check if the day is less than 31, month is less than 12 and so on.

  •  Tags:  
  • Related