开发者

Why Java SimpleDateFormat().parse() is printing weird formate?

开发者 https://www.devze.com 2022-12-23 20:59 出处:网络
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\");

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);
                Sy开发者_运维百科stem.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.


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

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


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


If you want to print the date in the original format, use the format method:

System.out.println("Date Time : "+ dateFormat.format(today));

the "weird" format comes from Date's toString implementation, the javadoc says:

Converts this Date object to a String of the form:

dow mon dd hh:mm:ss zzz yyyy

"I just wanted to keep the same format of the original String date and make it into a Date object."

The Date Object is intended to represent a specific instant in time, you can't keep the format of the original string into it, that's why we have the DateFormat Class.


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) );


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消