很多时间时候,我们会要获取当前时间的前一段时间发生过的事,如:在用户想要查看当前时间前一个小时的数据的时候,用户只需要输入60即可,调出来的就是前六十分钟的 数据,又或者说,知道当前时间,就想获取它的前一个具体时间点,或者后一个时间点, 这就用到了calendar,
//这里是直接写的一个java文件,
package
com.jj;
import
java.text.SimpleDateFormat;
import
java.util.Calendar;
public
class
Time1 {
public
static
void
main(String[]
args
) {
String
currentTime
=time1(0);
String
changeTime
=time1(-30);
//前三十分钟
System.
out
.println(
“当前时间 –:”
+
currentTime
+
“\n提前三十分钟\n更改后的时间—:”
+
changeTime
);
}
public
static
String time1(
int
a
) {
String
currentTime
=
“”
;
//当前时间
Calendar
cal
=Calendar.getInstance();
//这里用的是分钟,也可以用小时,或者是天…
cal
.set(Calendar.
MINUTE
, Calendar.
MINUTE
+
a
);
//当前分钟的前后分钟,
//格式化指定形式的时间
currentTime
=
new
SimpleDateFormat(
“yyyy-MM-dd HH:mm:ss”
).format(
cal
.getTime());
//获取到完整的时间
return
currentTime
;
}
}