将字符串日期转换为Java Date对象 [英] Convert String dates into Java Date objects

查看:171
本文介绍了将字符串日期转换为Java Date对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复:

计算Java日期的差异

如何计算Java中的时间间隔并格式化输出?

说你被给了两个日期作为字符串,他们是这样的格式 8/11/11 9:16:36 PM 我将如何将它们转换为java Date对象,以便我可以计算两个日期之间的差异?

Say you were given two dates as strings and they are in this format 8/11/11 9:16:36 PM how would I go about converting them to java Date objects so that I can then calculate the difference between two dates?

推荐答案

只要两个时间都是GMT / UTC,你可以执行 date1.getTime() - date2.getTime(),然后将结果除以86400000得到天数。其余的可能非常直观。

As long as both times are in GMT/UTC, you can do date1.getTime() - date2.getTime() and then divide the result by 86400000 to get number of days. The rest is probably pretty intuitive.

编辑 - 根据编辑的问题

EDIT -- based on edited question

要将字符串转换为日期,请使用 SimpleDateFormat 类。

To convert Strings into dates, use the SimpleDateFormat class.

String yourDateString = "8/11/11 9:16:36 PM";
SimpleDateFormat format =
            new SimpleDateFormat("MM/dd/yy HH:mm:ss a");
Date yourDate = format.parse(yourDateString);

这篇关于将字符串日期转换为Java Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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