• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps SimpleDateFormat

creatiive

Lurker
hey,

im trying to parse a datetime... and im having a lot of trouble. The code i have is pretty simple, just trying to parse a string in to a Date object.

In this code, the 'datetime' variable is "01-13-2010 21:56".
After the df.parse(datetime) line, the date is "Sat Jan 01 21:56:00 GMT+00:00 2011"... which is wrong.

Then, after the calls to getYear, etc... the values are different again!
mYear = 111
mMonth = 0
mDay = 6
mHour = 21
mMinute = 56

I've tried lots of different SimpleDateFormat formats and i cannot get any to work! Any help here would be great!

Code:
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm");
    if (datetime != null && !datetime.equals("")) {
	Date date = df.parse(datetime);
	mYear = date.getYear();
	mMonth = date.getMonth();
	mDay = date.getDay();
	mHour = date.getHours();
	mMinute = date.getMinutes();
}
 
Ugh, I get the same kind of problems in Lotus Notes. Horrible. Here's what's going on:

Your string date appears to be 'mm-dd-yyyy' (based on the '13' in there), but when you try to parse it, the day becomes '1' and the year shifts up by one. Why? Because the actual date format is 'dd-mm-yyyy', and so the month is read as 12+1, meaning January of the following year. This is most likely also the cause for getYear returning '111', but I'm not so sure what's going on with getDay.

So, looking at your specific code, it seems to me that you are telling SimpleDateFormat to use a wrong format to interpret your given datetime string. Shouldn't you be using "new SimpleDateFormat("MM-dd-yyyy HH:mm")"? I'd need to see a bit more of the surrounding context to be certain, but you can probably check it yourself.
 
If that's what you sense, then I'm very glad you asked -- because I do try my best to NOT be hostile. :) If anything, it was meant as a tip for good practice, perhaps phrased as a friendly jab. I do apologise.

No hard feelings I hope!
 
Back
Top Bottom