# 时间操作
# 介绍
[TOC]
# java 获取当天(今日)零点零分零秒
1.日期格式的
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date zero = calendar.getTime();
1
2
3
4
5
6
2
3
4
5
6
2.时间戳
long current = System.currentTimeMillis();
long zero = current/(1000*3600*24)*(1000*3600*24) - TimeZone.getDefault().getRawOffset();
1
2
2
# 获取当前或者未来时间
public class TimeClass {
public static void main(String[] args) {
// 获取一个小时以后的时间
Calendar calendar = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
calendar.set(Calendar.HOUR_OF_DAY,
calendar.get(Calendar.HOUR_OF_DAY) + 1);
System.out.println("当前的时间:" + df.format(new Date()));
System.out.println("一个小时前的时间:" + df.format(calendar.getTime()));
// 获取一秒以后
calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND,
calendar.get(Calendar.SECOND) + 1);
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("一秒以后的时间:" + df.format(calendar.getTime()));
// 获取一天以后的时间
calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR,
calendar.get(Calendar.DAY_OF_YEAR) + 1);
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("一天以后的时间:" + df.format(calendar.getTime()));
// 获取一个星期以后的时间
calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR,
calendar.get(Calendar.WEEK_OF_YEAR) + 1);
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("一个星期以后的时间:" + df.format(calendar.getTime()));
// 获取一个月以后的时间
calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("一个月以后的时间:" + df.format(calendar.getTime()));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
← 定时清理Tomcat下temp目录 网络 →