I have one date in format of date = "2022-07-03 10:09:19"
Need to get difference of months from Today date and time
CodePudding user response:
You can leverage java.time
library. Here is a sample code snippet:
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
val dateOld = "2022-07-03 10:09:19".replace(" ", "T")
val dateNew = "2022-11-03 10:09:19".replace(" ", "T")
val l1 = LocalDateTime.parse(dateOld)
val l2 = LocalDateTime.parse(dateNew)
val months = ChronoUnit.MONTHS.between(l1, l2)
For calculating from current time you can use:
val date = "2021-07-03 10:09:19".replace(" ", "T")
val l1 = LocalDateTime.parse(date)
val l3 = LocalDateTime.now()
val months = ChronoUnit.MONTHS.between(l1, l3)
Hope this helps !!
CodePudding user response:
Use ChronoUnit to solve it
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime previousDate = LocalDateTime.parse(date, formatter);
LocalDateTime now = LocalDateTime.now();
long diffMonths = ChronoUnit.MONTHS.between(now, previousDate);
CodePudding user response:
Use java.time
if possible
You can parse the datetime String
, add a time zone and take the current day or moment in the same time zone. Then you can extract the date and calculate the Period.between
those two.
Here's an example in Java:
public static void main(String[] args) {
// example input
String someTime = "2022-07-03 10:09:19";
// prepare a formatter that can parse such a String
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
// prepare the time zone
// (I will use UTC, but the zone depends on the one of the input)
ZoneId utc = ZoneId.of("UTC");
// parse the String, apply the zone and directly extract the date
LocalDate then = LocalDateTime.parse(someTime, dtf)
.atZone(utc)
.toLocalDate();
// get the date of today in the zone
LocalDate today = LocalDate.now(utc);
// calculate the period between the two dates
long months = ChronoUnit.MONTHS.between(then, today);
// prepare some meaningful message to be printed
String msg = String.format(
"The difference in months between %s (then) and %s (today) is %d months",
then, today, months);
// and actually print it
System.out.println(msg);
}
Output:
The difference in months between 2022-07-03 (then) and 2022-08-03 (today) is 1 months
CodePudding user response:
Parse the given date to an instance of java.time.LocalDateTime
, then you can get an instance of java.time.Period
for the two dates, and from that, you can get the months.
In Java:
final DateTimeFormatter parser = … // An appropriate parser for the given format
final var otherDate = LocalDateTime.parse( dateString, parser );
final var deltaPeriod = Period.between( LocalDateTime.now(), otherDate );
final var result = deltaPeriod.getYears() * 12 deltaPeriod.getMonths(); // or use Period::toTotalMonths()