Date conversions are very common scenarios in any application.,
Java Provides SimpleDateFormat class for String to Date, Date to String conversions.
The below example shows
- How String format can be converted to Date Format.
- How to find difference between 2 Dates.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.text.SimpleDateFormat; import java.util.Date; class Example { public static void main(String args[]) { String date = "11/13/2018"; try { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); Date parseDate = sdf.parse(date); System.out.println(parseDate); long differenceInMillis = new Date().getTime() - parseDate.getTime(); long differenceInDays = ((differenceInMillis/1000)/(60*60*24)); long year = differenceInDays/365; System.out.println("DifferenceInDays:"+differenceInDays); System.out.println("Age:"+year); } catch(Throwable t) { t.printStackTrace(); } } } |
Output
1 2 3 |
Tue Nov 13 00:00:00 UTC 2018 DifferenceInDays:1099 Age:3 |