SimpleDateFormat的使用详解

来源:互联网 发布:梦里花落知多少沐紫苏 编辑:程序博客网 时间:2024/05/20 07:15

之前经常会用到SimpleDateFormat来格式化时间和日期,今天又遇到了。却发现还是要google,说明自己没有掌握它。现在把它的一些用法整理出来。

大多数情况下,我们用到的是SimpleDateFormat(String pattern) 这个构造函数:其中格式可以进行如下定义。

eg:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

每个字母定义如下

LetterDate or Time ComponentPresentationExamplesGEra designatorTextADyYearYear199696MMonth in yearMonthJulyJul07wWeek in yearNumber27WWeek in monthNumber2DDay in yearNumber189dDay in monthNumber10FDay of week in monthNumber2EDay in weekTextTuesdayTueaAm/pm markerTextPMHHour in day (0-23)Number0kHour in day (1-24)Number24KHour in am/pm (0-11)Number0hHour in am/pm (1-12)Number12mMinute in hourNumber30sSecond in minuteNumber55SMillisecondNumber978zTime zoneGeneral time zonePacific Standard TimePSTGMT-08:00ZTime zoneRFC 822 time zone-0800

然后可以使用继承自DateFormat的 format 这个方法来对日期进行格式化。举例如下:

                import java.text.SimpleDateFormat;
SimpleDateFormat sdf0 = new SimpleDateFormat("Gyyyy年MM月dd日 HH时mm分ss秒");SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 第w周  第D天 HH:mm:ss");SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 时区1:z");SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 时区1:Z");SimpleDateFormat sdf5 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 小时1-24:k");SimpleDateFormat sdf6 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 微秒:S");Date currentDate = new Date(System.currentTimeMillis());System.out.println(sdf0.format(currentDate));System.out.println(sdf1.format(currentDate));System.out.println(sdf2.format(currentDate));System.out.println(sdf3.format(currentDate));System.out.println(sdf4.format(currentDate));System.out.println(sdf5.format(currentDate));System.out.println(sdf6.format(currentDate));


结果如下:

公元2011年07月25日 12时08分01秒2011/07/25 12:08:012011-07-25 第31周  第206天 12:08:012011-07-25 12:08:01 时区1:CST2011-07-25 12:08:01 时区1:+08002011-07-25 12:08:01 小时1-24:122011-07-25 12:08:01 微秒:250

原创粉丝点击