简体   繁体   中英

Java Date Formatting DateFormat

Can we use new DateFormat(); to create an object of DateFormat ?

DateFormat format = DateFormat.getDateInstance();

is used but can we use the following?

DateFormat df = new DateFormat(); 
df.getDateInstance();

使用SimpleDateFormat

DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm.ss");

DateFormat is an abstract class, like all abstract classes you cannot instantiate them. You can only instantiate a subclass of an abstract class provided the subclass is not abstract also. To know more about abstract classes, look at abstract classes tutorial by oracle

DateFormat is an abstract class with protected constructor.You can use SimpleDateFormat like this. This statement won't even compile.

  DateFormat d=new DateFormat();

The constructor is defined as

protected DateFormat()

which means you cannot call it like that. Neither can you do something like:

DateFormat df = DateFormat;

It does not provide any aliasing mechanism to avoid typing it. So you will have to always to do:

DateFormat df = DateFormat.getDateInstance();

Or you can use a subclass as @Verhagen has pointed out.

It is also an abstract class, but one way you could do it is use an anonymous constructor:

    java.text.DateFormat df = new java.text.DateFormat(){
        @Override
        public Date parse(String source, ParsePosition pos) {
            // TODO Auto-generated method stub
            return null;
        }
        @Override
        public StringBuffer format(Date date, StringBuffer toAppendTo,
                FieldPosition fieldPosition) {
            // TODO Auto-generated method stub
            return null;
        }
    };

but in this case you have to define what those methods do.

You can use SimpleDateFormat which is an implementation and not an abstract class as stated in @Verhagen answer, but be bareful with it, most of the times you got to use it in a ThreadLocal to avoid those problems.

It has some pretty bad side effects when used in a multi threaded environment.

With Java 8 the recomended is to use the new Date API

final DateTimeFormatter formatter =  
      DateTimeFormatter.ofPattern(dateTimeFormatPattern);  
   final String nowString = formatter.format(now8);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM