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
293 views
in Technique[技术] by (71.8m points)

java - How to properly format the date?

The function shown below returns the date, e.g. "Sat Sep 8 00:00 PDT 2010". But I expected to get the date in the following format "yyyy-MM-dd HH:mm". What's wrong in this code?

String date = "2010-08-25";
String time = "00:00";

Also in one laptop the output for,e.g. 23:45 is 11:45. How can I define exactly the 24 format?

private static Date date(final String date,final String time) {
       final Calendar calendar = Calendar.getInstance();
       String[] ymd = date.split("-");
       int year = Integer.parseInt(ymd[0]);
       int month = Integer.parseInt(ymd[1]);
       int day = Integer.parseInt(ymd[2]);
       String[] hm = time.split(":");
       int hour = Integer.parseInt(hm[0]);
       int minute = Integer.parseInt(hm[1]);
       calendar.set(Calendar.YEAR,year);
       calendar.set(Calendar.MONTH,month);
       calendar.set(Calendar.DAY_OF_MONTH,day);
       calendar.set(Calendar.HOUR,hour);
       calendar.set(Calendar.MINUTE,minute);
       SimpleDateFormat dateFormat =  new SimpleDateFormat("yyyy-MM-dd HH:mm");
       Date d = calendar.getTime();
       String dateString= dateFormat.format(d);
       Date result = null;
       try {
            result = (Date)dateFormat.parse(dateString);
       } catch (ParseException e) {
            e.printStackTrace();
       }
       return result;
    }
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

What's wrong in this code?

You seem to be expecting the returned Date object to know about the format you've parsed it from - it doesn't. It's just an instant in time. When you want a date in a particular format, you use SimpleDateFormat.format, it's as simple as that. (Well, or you use a better library such as Joda Time.)

Think of the Date value as being like an int - an int is just a number; you don't have "an int in hex" or "an int in decimal"... you make that decision when you want to format it. The same is true with Date.

(Likewise a Date isn't associated with a specific calendar, time zone or locale. It's just an instant in time.)


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

...