Is it possible to get java.util.Date object with specific format?

别等时光非礼了梦想. 提交于 2019-12-30 11:12:07

问题


I would like to ask about the usage of java.util.Date. Here is my sample class

         public class DateConverter {
           public static void main(String[] args) {
                  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
                  Date today = new Date();
                  String dateAsString_format = simpleDateFormat.format(today);
                  System.out.println("Formatted Date String (String datatype): " + dateAsString_format);
                  Date parsedDate = null;
                  try {
                      parsedDate = simpleDateFormat.parse(dateAsString_format);
                  } catch (ParseException e) {
                      e.printStackTrace();
                  }
                  System.out.println("Parse Date (Date datatype): " + parsedDate);
               }
            }

My output is

         Formatted Date String (String datatype): 06/10/2013
         Parse Date (Date datatype): Sun Oct 06 00:00:00 MMT 2013

But I would like to get the following output

         Formatted Date String (String datatype): 06/10/2013
         Parse Date (Date datatype): 06/10/2013

Is it possible to get Date object with specific format?


回答1:


Is it possible to get Date object with specific format?

No. Date doesn't have any format. It represents the number of milliseconds since epoch. You only get the formatted string using SimpleDateFormat, which you already did.

Printing Date invokes the overridden Date#toString() method, which uses a default format, in which every Date is printed.

Here's how Date#toString() source looks like:

public String toString() {
    // "EEE MMM dd HH:mm:ss zzz yyyy";
    BaseCalendar.Date date = normalize();
    StringBuilder sb = new StringBuilder(28);
    int index = date.getDayOfWeek();
    if (index == gcal.SUNDAY) {
        index = 8;
    }
    ....  // some more code
}

So the format used is "EEE MMM dd HH:mm:ss zzz yyyy"




回答2:


Yes, extend Date adding the format field and override toString method, something along the lines of

public class DateWithFormat extends Date {
   String format; // Assign as appropriate
   public String toString() {
     return new SimpleDateFormat(format).format(this));
   } 
}


来源:https://stackoverflow.com/questions/19207477/is-it-possible-to-get-java-util-date-object-with-specific-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!