日期格式化

在java中使用DateFormat类(国际化日期)将日期格式化:

DateFormat 类可以将一个日期/时间对象格式化为表示某个国家地区的日期/时间字符串。

DateFormat 类除了可按国家地区格式化输出日期外,它还定义了一些用于描述日期/时间的显示模式的 int 型的常量,包括FULL, LONG, MEDIUM,DEFAULT, SHORT,实例化DateFormat对象时,可以使用这些常量,控制日期/时间的显示长度。

DateFormat的几种显示模式:

SHORT模式完全是数字的,在中文环境下显示为“05-9-15下午4:41”;在英文环境下为“9/15/05 4:41 PM”。

MEDIUM模式比SHORT模式长些,在中文环境显示为“2005-9-15 16:41:20”;在英文环境下显示为“Sep 15, 2005 4:41:20 PM”。

LONG模式比MEDIUM模式更长一些,在中文环境下显示为“2005年9月15日 下午04时41分20秒”;在英文环境下显示为“September 15, 2005 4:41:20 PM CST”。

FULL模式指定日期/时间的完整格式,在中文环境下显示为“2005年9月15日 星期四 下午04时41分20秒 CST”;在英文环境下,这个日期/时间显示为“Thursday, September 15, 2005 4:41:20 PM CST”。

实例化DateFormat类

getDateInstance(int style, LocaleaLocale):以指定的日期显示模式和本地信息来获得DateFormat实例对象,该实例对象不处理时间值部分。

getTimeInstance(int style, LocaleaLocale):以指定的时间显示模式和本地信息来获得DateFormat实例对象,该实例对象不处理日期值部分。

getDateTimeInstance(intdateStyle, int timeStyle, Locale aLocale):以单独指定的日期显示模式、时间显示模式和本地信息来获得DateFormat实例对象。

DateFormat 对象的方法:

format: 将日期/时间对象格式化为符合某个本地环境习惯的字符串。

parse:将符合某个本地环境习惯的日期/时间字符串解析为日期/时间对象

注意:parse和format完全相反,一个是把date时间转化为相应地区和国家的显示样式,一个是把相应地区的时间日期转化成date对象,该方法在使用时,解析的时间或日期要符合指定的国家、地区格式,否则会抛异常。

DateFormat对象通常不是线程安全的,每个线程都应该创建自己的 DateFormat  实例对象

例如:

(1)、创建一个date对象,并把date对象中表示日期部分的时间值,以及表示时间部分的时间值,分别以short、long模式进行格式化输出(国家设置为中国)

  

      //获取时间值

      Date date = new Date();

      String dateStr = date.toString();

      System.out.println("获取时间:" +dateStr);

      

      //date和time值按照short模式格式化输出

      DateFormat shortDF = DateFormat.getDateTimeInstance(SimpleDateFormat.SHORT,SimpleDateFormat.SHORT,Locale.CHINA);

      System.out.println("short模式的时间:" + shortDF.format(date));

      //date和time值按照long模式格式化输出

      DateFormat longDF = DateFormat.getDateTimeInstance(SimpleDateFormat.LONG,SimpleDateFormat.LONG,Locale.CHINA);

      System.out.println("long模式的时间:" + longDF.format(date));


 

       (2)、将时间值:09-11-28 上午10时25分39秒  CST,反向解析成一个date对象

   String str = "09-11-28 上午10时25分39秒 CST";

      String dateStr = str.toString();

      System.out.println(dateStr);

   

      //反向解析

      DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.FULL,Locale.CHINESE);

   

      String dateS = df.parse(dateStr).toString();

      System.out.println("反向解析出的结果:" + dateS);

 

使用标签实现日期格式化:

日期格式化<fmt:formatDatevalue=“” pattern=“” dateStyle="" timeStyle=" " type=" "/>

value:要格式化的日期

pattern:日期格式化的格式

如:

 //date和time值按照short模式格式化输出

<fmt:formatDate value="<%=new Date() %>" dateStyle="short"timeStyle="short" type="both"/><br>

//date和time值按照long模式格式化输出

 <fmt:formatDate value="<%=new Date() %>" dateStyle="long"timeStyle="long" type="both"/>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章