黑马程序员技术交流社区

标题: SimpleDateFormat的扩展 [打印本页]

作者: 游呤人    时间: 2015-7-21 02:33
标题: SimpleDateFormat的扩展
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
*
* SimpleDateFormat的SimpleDateFormat一个案例的实现,
* 英国人看时间的格式是  21-07-2015  01:53:50
*
                                                          01 Jan 1970  12:00:00
       
* 首先来完成第一个程序,dd-MM-YYYY  hh:mm:ss这个格式化方式很简单但是第二怎样的呢?
*通过API发现程序  EEE, MMM d, ''yy"        Wed, Jul 4, '01   那么就把格式定义成dd MMM YYYY hh:mm:ss 这样的方式
*可是这个现实实在太残酷了
*                                 01 一月 1970  12:00:00
                                 21 七月 2015  02:08:40
                                这是因为我们当前所处的环境是中文环境,
                                所以更改操作系统的语言环境即可,但是我不想更改我的语言环境,那怎么办呢?
                                在API中有这样的方法
                                DateFormatSymbols getDateFormatSymbols()  获取此日期格式的日期和时间格式符号的一个副本。
                                void setDateFormatSymbols(DateFormatSymbols newFormatSymbols) 设置此日期格式的日期和时间格式符号。  
                                它们都在操作时间格式符号 显然DateFormatSymbols 保存的时间格式符号
                                那么就看看这个类,发现这里面有两个方法
                                String[] getShortMonths()  获取简短形式的月份字符串。
                          String[] getMonths()         获取月份字符串。
                                void setMonths(String[] newMonths)  设置月份字符串。
                void setShortMonths(String[] newShortMonths) 设置简短形式的月份字符串。
                 void setShortMonths(String[] newShortMonths) 设置简短形式的月份字符串
                发现 void setShortMonths(String[] newShortMonths)方法是我们可能想要的,于是就大胆的尝试一下
               定义一个DateFormatSymbols
                DateFormatSymbols dfs = new DateFormatSymbols();
                使用DateFormatSymbols.setShortMonths传入一个匿名字符串数组
                                dfs.setShortMonths(new String[]{"Jan","Feb","Mar","April","May","Jun","July","Aug","Sep","Oct","Nov","Dec"});
                将DateFormatSymbols对象通过format4.setDateFormatSymbols(dfs);传入SimpleDateFormat中

                               
* */
public class DataDome {
        public static void main(String[] args) throws ParseException {
                Date date=new Date();
                DateFormat format3= new SimpleDateFormat("dd-MM-YYYY  hh:mm:ss");
                System.out.println(format3.format(new Date()));
                SimpleDateFormat format4= new SimpleDateFormat("dd MMM YYYY  hh:mm:ss");
                DateFormatSymbols dfs = new DateFormatSymbols();
                dfs.setShortMonths(new String[]{"Jan","Feb","Mar","April","May","Jun","July","Aug","Sep","Oct","Nov","Dec"});
                format4.setDateFormatSymbols(dfs);
               
                System.out.println(format4.format(new SimpleDateFormat("MM").parse("01").getTime()));
                System.out.println(format4.format(new Date()));
        }
}







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2