Question:
How to write a program in Java that calculates the difference between 2 user input dates?
Code:
import java.util.*; import java.text.*; public class CompareDates { public static void main( String[] args ) { Scanner sc = new Scanner(System.in); System.out.print("Enter date1 (yyyy-MM-dd): "); String d1 = sc.nextLine(); System.out.print("Enter date2 (yyyy-MM-dd): "); String d2 = sc.nextLine(); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = sdf.parse(d1); Date date2 = sdf.parse(d2); System.out.println("Date1: " + sdf.format(date1)); System.out.println("Date2: " + sdf.format(date2)); long diff = date1.getTime() - date2.getTime(); diff = diff / (1000L*60L*60L*24L); System.out.println("Delta: " + diff + " days"); } catch(ParseException ex) { } } }
Output:
$ java CompareDates Enter date1 (yyyy-MM-dd): 2000-11-11 Enter date2 (yyyy-MM-dd): 2000-10-11 Date1: 2000-11-11 Date2: 2000-10-11 Delta: 31 days