Java时间处理

转载自:http://my.oschina.net/brucelee80/blog

总体

Java时间处理


String <-> Date

String time = "1949-10-01 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(time);

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
String time2 = sdf2.format(date);


Long <-> String

long current = System.currentTimeMillis();
Date date = new Date(current);

long dateLong = date.getTime();


Date <-> Calendar

Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

Date calDate = calendar.getTime();


Long <-> Calendar

long current = System.currentTimeMillis();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(current);

long calLong = calendar.getTimeInMillis();


SimpleDateFormat解析模式

注:文本可以使用单引号 (') 引起来,以免进行解释。"''" 表示单引号。

字母

日期或时间元素

表示

示例

G

Era 标志符

Text

AD

y

Year

1996; 96

M

年中的月份

Month

July; Jul; 07

w

年中的周数

Number

27

W

月份中的周数

Number

2

D

年中的天数

Number

189

d

月份中的天数

Number

10

F

月份中的星期

Number

2

E

星期中的天数

Text

Tuesday; Tue

a

Am/pm 标记

Text

PM

H

一天中的小时数(0-23)

Number

0

k

一天中的小时数(1-24)

Number

24

K

am/pm 中的小时数(0-11)

Number

0

h

am/pm 中的小时数(1-12)

Number

12

m

小时中的分钟数

Number

30

s

分钟中的秒数

Number

55

S

毫秒数

Number

978

z

时区

General time zone

Pacific Standard Time; PST; GMT-08:00

Z

时区

RFC 822 time zone

-0800


获取系统当前时间

方法1:new Date()

方法2:System.currentTimeMillis()

方法3:Calendar.getInstance()


获取星期、月份、时区、时间加减等

Calendar拥有强大的处理功能,可处理以上需求。

另外,如果想做时间的比较,可使用Date的after和before方法,Date实现了Comparable接口

转载自:http://my.oschina.net/brucelee80/blog

你可能感兴趣的:(java时间处理,Java日期格式化)