Convert String to date to calculate the difference

2019-09-08 20:27发布

I have 2 dates in a String format (ex. 2012-04-23, 2012-03-08), and I want to find the difference between them.

What is the best way to calculate that in Java?

I am just concerned with the date and not the time

标签: java string date
5条回答
Melony?
2楼-- · 2019-09-08 20:34

If you are willing to add a third party jar to your project, then check the jodatime

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");

DateTime dt = formatter.parseDateTime(your-string);

  • Find the difference between them -interval

Interval interval = new Interval(time1, time2);

You also might want to check the difference between interval and duration which are concepts in jodatime lib

查看更多
你好瞎i
3楼-- · 2019-09-08 20:35

Use SimpleDateFormat to turn the strings into Date objects and use the getTime() method on Date to get the equivalent time in milliseconds. Take the difference between the two milliseconds values.

查看更多
Anthone
4楼-- · 2019-09-08 20:42

You can convert string to date using:

String dateString = "2012-04-23";
Date date = new SimpleDateFormat("yyyy-mm-dd").parse(dateString);

You can read about SimpleDateFormat further here.


As to difference between two dates, you can calculate it in milliseconds with:

int milliseconds = dateOne.getTime() - dateTwo.getTime();

getTime() returns the number of milliseconds since January 1, 1970.

To convert it in days, use:

int days = milliseconds / (1000 * 60 * 60 * 24)
查看更多
劳资没心,怎么记你
5楼-- · 2019-09-08 20:55

You may want to you DateFormat, Date and Calendar combination as below:

    DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date1 = dFormat.parse("2012-04-23");
    Date date2 = dFormat.parse("2012-03-08");
    long timeDifInMillis = date1.getTime() - date2.getTime();

    Date dateDiff = new Date(timeDifInMillis);
    Calendar diffCal = Calendar.getInstance();
    diffCal.setTime(dateDiff);
    System.out.println("Days="+diffCal.get(Calendar.DAY_OF_MONTH));
    System.out.println("Months="+diffCal.get(Calendar.MONTH));
    System.out.println("Years="+(diffCal.get(Calendar.YEAR)-1970));
查看更多
We Are One
6楼-- · 2019-09-08 20:57

Check SimpleDateFormat, it has a parse function.

查看更多
登录 后发表回答