1、Date类
Date类定义为:
public class Date
extends Object
implements Serializable, Cloneable, Comparable<Date>
如果想取得日期时间,最简单的就是直接使用java.util.Date类对象,只要实例化类对象就可以取得时间,如:
import java.util.Date;
public class test{
public static void main(String args[]){
System.out.println(new Date());
}
}
但是此时取得的时间如下
Mon Mar 13 08:21:47 CST 2017
但是此时间格式不易看懂,所以java中提供有Date和long之间相互转换的操作:
- 将long变为Date: public Date(long date)
- 将Date变为long:public long getTime()
- 将Date变为String:public String toString()
2、DateFormat类
在java.util.Date类取得的时间的显示格式不符合Chinese的习惯要求,所以此时可以对此类进行格式化操作,将其变为我们习惯的日期格式。
DateFormat类和MessageFormat类都属于Format类的子类,专门用于格式化数据使用。DateFormat类的定义如下:
public abstract class DateFormat
extends Format
此类常用方法有:
方法 | 描述 |
---|---|
public static final DateFormat getDateInstance() | 取得默认的对象 |
public static final DateFormat getDateInstance(int style,Locale aLocale) | 根据Local得到对象 |
public static final DateFormat getDateTimeInstance() | 得到日期时间对象 |
public static final DateFormat getDateTimeInstance(int dateStyle,int timeStyle,Locale aLocale) | 根据Local的到日期时间对象 |
示例:指定显示的风格:
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class DateFormatDemo{
public static void main(String args[]){
DateFormat date1 = null;
DateFormat date2 = null;
date1 = DateFormat.getDateInstance(DateFormat.YEAR_FIELD,new Locale("zh","CN"));
date2 = DateFormat.getDateTimeInstance(DateFormat.YEAR_FIELD,DateFormat.ERA_FIELD,new Locale("zh","CN"));
System.out.println("DATE :" + date1.format(new Date()));
System.out.println("DATETIME :" + date2.format(new Date()));
}
}
以上的日期时间已经被格式化,格式是其默认的时间显示格式,但是如果要想的到用户自己需要的日期时间显示格式,则必须通过DateFormat的子类SimpleDateFormat类完成。
3、SimpleDateFormat类
如果需要对日期格式进行处理的话就需要使用SimpleDateFormat类来完成,该类定义如下:
java.lang.Object
java.text.Format
java.text.DateFormat
java.text.SimpleDateFormat
public class SimpleDateFormat
extends DateFormat
所有的日期的转换都在DateFormat类中提供,而SimpleDateFormat类只需要提供具体的处理格式件即可,在SimpleDateFormat类中定义有如下格式标记:
年(yyyy)、月(MM)、日(dd)、时(HH)、分(mm)、秒(ss)、毫秒(SSS)
在SimpleDateFormat类里主要使用如下的方法进行处理:
- 构造方法:public SimpleDateformat(String patten)
- 将Date格式化为String:public final String format(Date date)
- 将String变为Date:public String parse(String source) throws ParseException