Java基础入门 DateFormat类

在之前的学习中,有Date类用于表示时间和日期,但是打印Date对象时都是以英文默认格式输出的,若是将Date对象表示的日期以指定的格式输出,例如输出中文日期,就需要用到DateFormat类。具体用法下面代码为例:

import java.text.*;
import java.util.*;
public class Main{
	public static void main(String[] args)throws Exception{
        Date date=new Date();
        DateFormat fullFormat=DateFormat.getDateInstance(DateFormat.FULL);
        DateFormat longFormat=DateFormat.getDateInstance(DateFormat.LONG);//full和long对应的都是日期
        DateFormat mediumFormat=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);
        DateFormat shortFormat=DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);//medium和short对应的都是日期和时间
        System.out.println("当前日期完整格式为:"+fullFormat.format(date));
        System.out.println("当前日期长格式为:"+longFormat.format(date));
        System.out.println("当前日期普通格式为:"+mediumFormat.format(date));
        System.out.println("当前日期短格式为:"+shortFormat.format(date));
	}
}

另外在DateFormat类中还提供了一个parse()方法,能够将一个字符串解析成Date对象。但是它要求字符串必须符合日期/时间的格式要求,否则就会抛出异常。下面通过一个小程序演示一下:

import java.text.*;
public class Main{
	public static void main(String[] args)throws Exception{
        DateFormat dfl=DateFormat.getDateInstance(DateFormat.FULL);
        String dl="2018年8月13日 星期一";
        System.out.println("当前日期短格式为:"+dfl.parse(dl));
	}
}

!!!!需要注意的是字符串一定要符合格式要求!!!

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/81635808
今日推荐