Java常用时间处理

6/6/2020 JavaAPI

# 时间戳/date/string转换

// 获取当前时间戳
long l = System.currentTimeMillis(); // l=1589854992924
// 时间戳转date
Date date = new Date(l); // date=Tue May 19 10:23:12 CST 2020
// "yyyy-MM-dd hh:mm:ss"格式转date
String s = "2020-01-01 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date parse = sdf.parse(s);// parse=Wed Jan 01 00:00:00 CST 2020
// date获取时间戳
long time = parse.getTime(); // time=1577808000000
// date输出指定格式
String format = sdf.format(parse);//format=2020-01-01 00:00:00
// calendar 实现date增加一天
Date stratTime = simpleDateFormat.parse("2020-01-01");
Calendar calendar = Calendar.getInstance();
calendar.setTime(stratTime);
// 也可增加年/月
calendar.add(Calendar.DAY_OF_WEEK,1);
Date endTime = calendar.getTime();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

顺带记录两个空值判断写法

Integer a = Optional.ofNullable(null).orElse(new Integer(1)); // a=1
Integer a = getA()==null?1:getA();
1
2