繁体   English   中英

具有不同时区的两个日期之间的差异

[英]Difference between two dates with different timezones

我试图获得两个日期之间的差异,但我坚持将字符串转换为日期。

我的代码是:

    //create a date send it to the database as string
     Date currentDate = new Date(); // date looks like: Sat Sep 01 10:20:14 EEST 2012
     SaveToDB(currentDate.ToString());

在某些时候,我试图从数据库中检索日期:

       String dateStringFromDb = GetDateFromDB(); //Sat Sep 01 10:20:14 EEST 2012
       Date currentDate = new Date();

       //now i'm trying to covnert the dateStringFromDb into a Date, this throws an exception 

       Date dbDate = DateFormat.getInstance().parse(dateStringFromDb); //this throws exception

       long difference = currentDate.getTime() - dbDate.getTime(); // does this give me the correct difference in GMT even if timezones for the two dates are different?

你能指点我正确的解决方案吗?

不幸的是,数据库中的日期是作为String检索的,我无法将其更改为其他类型。 所以我需要将该字符串转换为Date()。

编辑:

例外情况是:

java.text.ParseException: Format.parseObject(String) failed
    at java.text.Format.parseObject(Unknown Source)
    at main.Program.main(Program.java:20)

我建议使用Joda Time API在Java中进行数据和时间相关的操作。 使用此API可以非常轻松地处理timezone和所有相关的转换细微差别。

您应指定DateFormat以匹配正在接收的字符串格式

例如。

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
String reformattedStr = myFormat.format(fromUser.parse(inputString));

获得所需格式的日期后,再应用日期算术运算

可以在http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html中找到DateString的其他格式说明符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM