-5

I am using two string variables to store two different dates. The dates are being stored in this format(May 28, 2019) and I need to find a difference in months.I am not able to figure if I need to first convert these dates to another format before doing the subtraction.

I am using getText() to get these dates from the following location //span[@class='expiry_date']

3 Answers3

0

You can use the DateFormat class to convert your String to a Date object. The easiest way to do addition or subtraction is using the Calendar class. You can convert the Date object to a Calendar object and do the calculation. Keep in mind the Calendar object won't keep the time information, but that doesn't seem to be an issue with your problem.

G_hi3
  • 588
  • 5
  • 22
0

The simplest approach is to use ChronoUnit#between method:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MMMM dd, yyyy", Locale.US );
LocalDate d1 = LocalDate.parse( "May 28, 2019", formatter );
LocalDate d2 = LocalDate.parse( "September 02, 2020", formatter );

long diff = ChronoUnit.MONTHS.between( d1, d2 );   // 15 full months
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
0

Coming to the point you gave To figure out if you need to first convert these dates to another format before doing the subtraction. Best approach you should take is that first convert dates to Java 8 LocalDate and then find the difference

Here is the sample code may be it can help you despite you have not shown your code effort.

    DateTimeFormatter customFormatter= DateTimeFormatter.ofPattern( "MMMM dd, yyyy",Locale.US);

    LocalDate date1 = LocalDate.parse( "April 01, 2019", customFormatter );
    LocalDate date2 = LocalDate.parse( "October 01, 2019", customFormatter );


    Period dateDifference = Period.between(date1, date2);
    System.out.println(dateDifference.toTotalMonths());
sandip
  • 129
  • 5
  • You should always define locale when working with language dependent data (e.g. month names). Your snippet won't work if run under differently configured JVM – Alex Salauyou May 28 '19 at 18:01