SimpleDateFormat的使用详解

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

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

eg:

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

每个字母定义如下

LetterDate or Time ComponentPresentationExamples
GEra designatorTextAD
yYearYear199696
MMonth in yearMonthJulyJul07
wWeek in yearNumber27
WWeek in monthNumber2
DDay in yearNumber189
dDay in monthNumber10
FDay of week in monthNumber2
EDay in weekTextTuesdayTue
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978
zTime zoneGeneral time zonePacific Standard TimePSTGMT-08:00
ZTime 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:01
2011-07-25 第31周  第206天 12:08:01
2011-07-25 12:08:01 时区1:CST
2011-07-25 12:08:01 时区1:+0800
2011-07-25 12:08:01 小时1-24:12
2011-07-25 12:08:01 微秒:250

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值