Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

java - Changing String date format

my current date format is : 08/11/2008 00:00

I need to convert this output to 2008/11/08 00:00 However, using the SimpleDateFormat as researched it is unable to do so and give me a totally different output, here are my codes as Follows :

SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy/MM/dd HH:mm")
Date starting= simpleDateFormat2.parse(startTime);
System.out.println("" + simpleDateFormat2.format(starting) + " real date " + startTime);

i do know that i am parsing in the right string given that the following output occurs :

0014/05/01 00:00 real date 08/11/2008 00:00

i am not too sure about how as to the mechanics detected 0014/05/01 00:00 instead of

2008/11/08 00:00

i look forward to all sugguestions Thanks in advance

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The first thing you need to do is parse the original value to a Date object

String startTime = "08/11/2008 00:00";
// This could be MM/dd/yyyy, you original value is ambiguous 
SimpleDateFormat input = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date dateValue = input.parse(startTime);

Once you have that done, you can format the dateValue any way you want...

SimpleDateFormat output = new SimpleDateFormat("yyyy/MM/dd HH:mm");
System.out.println("" + output.format(dateValue) + " real date " + startTime);

which outputs:

2008/11/08 00:00 real date 08/11/2008 00:00

The reason you're getting 0014/05/01 00:00 is SimpleDateFormat (when using yyyy/MM/dd HH:mm) is using 08 for the year, 11 for the month and 2008 for the day, it's doing an internal rolling of the values to correct the values to a valid date


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...