Home > OS >  how to get the calculated date and time in java?
how to get the calculated date and time in java?

Time:07-10

I have a date say 2022-07-10 as date (YYY/MM/dd) and time as 00:15

ie. 202207**10*****0015***

after subtracting 30 mins from above the result must be

2022-07-09 and time as 23:45

ie. 202207**09***2345***

other scenarios:

202207100030 -->202207100000

202207100010 -->202207092340

202207100035 -->202207100005

Could you please help me out with this.

CodePudding user response:

You need to use LocalDateTime.minus method:

DateTimeFormatter DATEFORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime d  = LocalDateTime.parse("2022-07-10 00:10", DATEFORMATTER);

LocalDateTime d2 = d.minus(Duration.ofMinutes(30));
LocalDateTime d3 = d.minus(30, ChronoUnit.MINUTES);
    
System.out.println(d2); //2022-07-09T23:40
System.out.println(d3); //2022-07-09T23:40

CodePudding user response:

What you want doesn't make sense. 2022-07-10 00:15 minus 30 minutes? That's not 2022-07-09 23:45. Not neccessarily, anyway. Maybe a timezone shift means it's 2022-07-10 00:45 (but, before the timezone change). Or it's 2022-07-09 22:45. Or perhaps it's 2022-07-01 23:45 - it's been a good long while but a locale can skip a day (last time: When one of the islands in the pacific decided to hop across the date line), or even half a month (last time: Russian revolution. It's still in the 1900s).

You can't 'do' date-diff math on Local date/time concepts; a time zone is required.

Once you've established one this is trivial:

  1. First, parse whatever you have into a LocalDate, LocalDateTime, OffsetDateTime, Instant, or ZonedDateTime object. These are all fundamentally different concepts - a key part of doing any time-based anything is figuring out what concept you're dealing with. For example, you seem to believe you're dealing with local date/times (no timezone), and yet also with a concept that can 'do' date diff math (which is mutually exclusive, hence, some more analysis of the situation is required).
  2. Then, transform what you have into the date/time concept you need to do the operation.
  3. Do the operation.
  4. Transform some more if needed.
  5. format it back to a string if you want.

If you try to shortcut and skip steps, it'll work, until it doesn't. Because date/time is just that hard.

For example:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMM**dd*****HHmm***");

LocalDateTime ldt = LocalDateTime.parse("202207**10*****0015***", dtf);

This is a good start; you now have an LDT object with the right year, month, day, minute, and hour.

Let's localize it somewhere and do the math:

ZonedDateTime zdt = ldt.atZone(ZoneId.of("Europe/Amsterdam"));
zdt = zdt.minusMinutes(30);
System.out.println(zdt.format(dtf));

Prints 202207**09*****2345***; I assume that's what you want.

  • Related