AndroidDev
AndroidDev

Reputation: 21237

Converting a string to a date - Inaccurate result

I have a string that looks like this: 2013-08-18 I need to convert this string into something that I can use to compare to another Date to see how many days have elapsed between the two. I came up with the following code to get it into a Calendar type, which is what my other variable is in. However, I'm getting inconsistent results that I don't understand. Here is my code:

String prefDate = prefs.getString("last_update", "2000-01-01");
System.err.println("oncreate prefDate: " + prefDate);

SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
Date date = new Date();
date = df.parse(prefDate);
Calendar last_update = Calendar.getInstance();
last_update.setTime(date);

Date verify = new Date(last_update.getTimeInMillis());
System.err.println("verify: " + verify);

The output looks like this:

oncreate prefDate: 2013-08-18

verify: Fri Jan 18 00:08:00 MST 2013

I'm not particularly concerned about the difference in formatting between the two outputs. But what is clearly wrong is that the outcome of all of this is off by 8 months - a bit outside of my error tolerance. Can anyone see what I am missing?

Thanks!

Upvotes: 0

Views: 61

Answers (1)

Jigar Joshi
Jigar Joshi

Reputation: 240860

change yyyy-mm-dd to yyyy-MM-dd and refer Documentation of SimpleDateFormat for detailed information

Upvotes: 3

Related Questions