0

On the web site I'm working with the dates object is created are presented in format like:
Jun 8th 2022 16:31:22
I need to validate the creation date is within the last 5 minutes.
So, I can get the current local date / time and then compare it with the date parsed from string got from the site.
But I can't find the date format matching the 8th day of month.
Without it I would use format like this:

SimpleDateFormat sdf = new SimpleDateFormat("MMM DD YYYY hh:mm:ss");

And then compare these dates but how can I handle xth day of month?

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • 1
    My first thought is to use a regular expression and replace the `th` and `st` and `nd` (or what ever fun sufix they come up with) – MadProgrammer Jun 09 '22 at 08:38
  • 2
    `DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d['st']['nd']['rd']['th'] yyyy HH:mm:ss", Locale.ENGLISH)` – MadProgrammer Jun 09 '22 at 08:44
  • @Abra looks like it should work, yes. I need to check this. Thanks! – Prophet Jun 09 '22 at 08:44
  • 1
    First, **don't** use `SimpleDateFormat`, for it's obsolete. Use `DateTimeFormatter` instead. – MC Emperor Jun 09 '22 at 09:11
  • 1
    Second, you can utilize the `DateTimeFormatterBuilder` as well, without replacing text. [See here](https://stackoverflow.com/a/72557618/507738) – MC Emperor Jun 09 '22 at 09:12
  • Thanks a lot @MCEmperor! I don't think I will create a map like you showing there, removing the suffix is good enough for me. Now I just need to find how exactly to implement the code checking the received date is within the last X seconds. There are many different solutions for that and so far it's not clear with one should I take.. Time formatting is not what I'm doing each day :) – Prophet Jun 09 '22 at 09:20
  • 1
    As soon as you have a `LocalDateTime`, `OffsetDateTime` or `ZonedDateTime` called `dateTime`, for example, and an `int` or `long x`, you can easily find out if this `dateTime.isBefore(dateTime.minusSeconds(x))`. – deHaar Jun 09 '22 at 09:43
  • @deHaar Looks like this is now what I need. I need to parse date/time from the string I mentioned and validate it is in the range of some fixed interval of X seconds from now. While you here using the same `dateTime` object. – Prophet Jun 09 '22 at 10:23
  • 1
    That was just an example as a reaction to your *within the last X seconds* comment. I thought that last X seconds were related to the `dateTime`. There are several possibilities, you can just define two `LocalDateTime`s and check if your current one is between them, like `isAfter` the older one and `isBefore` the newer… – deHaar Jun 09 '22 at 10:25

0 Answers0