DateFormat: 抽象类不能实例化,可以用getTimeInstance
, getDateInstance
, or getDateTimeInstance 得到对象。
具体介绍:https://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html
通过getDateInstance() 得到格式化对象
- SHORT is completely numeric, such as 12.13.52 or 3:30pm
- MEDIUM is longer, such as Jan 12, 1952
- LONG is longer, such as January 12, 1952 or 3:30:32pm
- FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST
DateFormat dfLONG = DateFormat.getDateInstance(DateFormat.LONG, Locale.CHINA);
SimpleDateFormat: 更简单得到格式化对象
参数含义:https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd E a HH:mm:ss");
测试代码:
package com.DL;
/**
* @author 段乐
* 日期格式化测试
*/
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class DateFormatTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Date date = new Date();
System.out.println(date);
/**
* 使用getDateInstance方法得到格式化对象
* */
DateFormat dfFULL = DateFormat.getDateInstance(DateFormat.FULL);
DateFormat dfLONG = DateFormat.getDateInstance(DateFormat.LONG, Locale.CHINA);
DateFormat dfMEDIUM = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINA);
DateFormat dfSHOT = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINA);
System.out.println(dfFULL.format(date));
System.out.println(dfLONG.format(date));
System.out.println(dfMEDIUM.format(date));
System.out.println(dfSHOT.format(date));
/**
* 压缩成Date类
*/
String myString = "2018年07月24日 星期二";
try {
Date myDate = dfFULL.parse(myString);
System.out.println(myDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* 使用SimpleDateFormat创建格式化对象
*/
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd E a HH:mm:ss");
System.out.println(sdf.format(date));
}
}
运行结果: