将String转换为日期以计算差异 [英] Convert String to date to calculate the difference

查看:99
本文介绍了将String转换为日期以计算差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个字符串格式的日期(例如2012-04-23、2012-03-08),我想找到它们之间的区别。

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

用Java计算该值的最佳方法是什么?

What is the best way to calculate that in Java?

我只关心日期而不是日期时间

I am just concerned with the date and not the time

推荐答案

您可以使用以下方式将字符串转换为日期:

You can convert string to date using:

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

您可以进一步阅读有关SimpleDateFormat的信息此处

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()返回毫秒数自1970年1月1日起。

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

要在几天内进行转换,请使用:

To convert it in days, use:

int days = milliseconds / (1000 * 60 * 60 * 24)

这篇关于将String转换为日期以计算差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆