Java 具有不同时区的两个日期之间的差异
我试图获得两个日期之间的差异,但我一直在将字符串转换为日期 我的代码是:Java 具有不同时区的两个日期之间的差异,java,android,Java,Android,我试图获得两个日期之间的差异,但我一直在将字符串转换为日期 我的代码是: //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()); 在某一点上,我;我正在尝试从数据库检索日期: Str
//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?
你能给我指出正确的解决办法吗
不幸的是,数据库中的日期是作为字符串检索的,我无法将其更改为其他类型。所以我需要将该字符串转换为Date()
编辑:
例外情况是:
java.text.ParseException: Format.parseObject(String) failed
at java.text.Format.parseObject(Unknown Source)
at main.Program.main(Program.java:20)
您应该指定一个DateFormat来匹配接收的字符串格式 例如 将两个日期都设置为所需格式后,应用日期算术运算 DateString的其他格式说明符可以在中找到
我建议在Java中使用API进行数据和与时间相关的操作。使用此API处理
时区
和所有相关的转换细微差别非常容易。@SiB更新了问题,但有一个例外
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
String reformattedStr = myFormat.format(fromUser.parse(inputString));