SimpleDateFormat的使用详解
来源:互联网 发布:梦里花落知多少沐紫苏 编辑:程序博客网 时间:2024/05/20 07:15
之前经常会用到SimpleDateFormat来格式化时间和日期,今天又遇到了。却发现还是要google,说明自己没有掌握它。现在把它的一些用法整理出来。
大多数情况下,我们用到的是SimpleDateFormat(String pattern) 这个构造函数:其中格式可以进行如下定义。
eg:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
每个字母定义如下
G
Era designatorTextAD
y
YearYear1996
; 96
M
Month in yearMonthJuly
; Jul
; 07
w
Week in yearNumber27
W
Week in monthNumber2
D
Day in yearNumber189
d
Day in monthNumber10
F
Day of week in monthNumber2
E
Day in weekTextTuesday
; Tue
a
Am/pm markerTextPM
H
Hour in day (0-23)Number0
k
Hour in day (1-24)Number24
K
Hour in am/pm (0-11)Number0
h
Hour in am/pm (1-12)Number12
m
Minute in hourNumber30
s
Second in minuteNumber55
S
MillisecondNumber978
z
Time zoneGeneral time zonePacific Standard Time
; PST
; GMT-08:00
Z
Time 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
- SimpleDateFormat的使用详解
- SimpleDateFormat 的 format 方法使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解(转)
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- SimpleDateFormat使用详解
- 文件重命名
- 初涉View
- [vs 2005]allocator
- Android开发googleMap+GPS定位中的关于Criteria一知半解问题
- android相关问题、网摘集锦
- SimpleDateFormat的使用详解
- 数据存储之SharedPreferences .
- HTML5介绍和部分功能实现
- 很有用的X264和ffmpeg的设置
- C++有哪几种情况只能用初始化列表,而不能用赋值?
- zz没有找到MSVCR90D.DLL的简单解决方法
- Service(1)之Context.startService()与Context.bindService()区别 .
- 管道,互斥
- 计算机专业学生需要学习的东西