views:

293

answers:

5

My input is String formated as the following:

3/4/2010 10:40:01 AM
3/4/2010 10:38:31 AM

My code is:

DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss aa");
            try
            {
                Date today = dateFormat.parse(time);
                System.out.println("Date Time : " + today);

            }
            catch (ParseException e)
            {
                e.printStackTrace();
            }

the output is:

Sun Jan 03 10:38:31 AST 2010
Sun Jan 03 10:40:01 AST 2010

I'm not sure from where the day (Sun) came from? or (AST)? and why the date is wrong? I just wanted to keep the same format of the original String date and make it into a Date object.

I'm using Netbeans 6.8 Mac version.

+6  A: 

Should be MM, not mm. The lowercase mm is for minutes, not months.

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
duffymo
+1  A: 

Printing the Date out using System.out.println() results in the toString() method being called on the Date object.

The format string used in toString() is what is causing the Day of the week and the timezone to appear in the output.

This is apart from the parsing mistake pointed out by Duffy.

Vineet Reynolds
Is there a way to prevent that?
MAK
+3  A: 

MM, not mm for months. You are using mm twice - and logically, it's the same things - minutes.

Bozho
+3  A: 
marcos
How can I print it without changing the format of Date?
MAK
@MAK, the Date Object contains no "format", you should not print it if you're looking to formated output
marcos
@marcos, I see...thank you very much for clarifying it.
MAK
+2  A: 

The answer is simple. You have displayed the Date.toString() value of today and not the intended dateFormat version. what you require is:

System.out.println("Date Time : " + dateFormat.format(today) );
FacilityDerek
but I need the String to be Date object!
MAK
The Date object can be passed as a parameter to other methods if that is what you require. To display the date in the format you chose requires you to use it as an argument to the format method of the dateFormat instance.
FacilityDerek