java使用Calendar类操作时间进行加减
程序员文章站
2022-06-24 21:56:39
...
Calendar是一个时间操作类,使用很方便
package com.example.hotelmanagement.controller;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @Author: 宇
* @introduction:
* @catalogue: com.example.hotelmanagement.controller
* @Date: 2021/6/2 11:19
* @Version: 1.0
*/
public class Time {
//操作时间,对时间进行相加减
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//当前时间
Date date = new Date();
System.out.println("===========================");
System.out.println(sdf.format(date));
//获取的是当前时间
Calendar calendar = Calendar.getInstance();
System.out.println("===========================");
System.out.println(sdf.format(calendar.getTime()));
//自定义一个时间
String time = "10:10:10";
SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
Calendar calendar1 = Calendar.getInstance();
//对起进行赋值
calendar1.setTime(sdf1.parse(time));
System.out.println("===========================");
System.out.println(sdf1.format(calendar1.getTime()));
//获取指定时分秒
int hour1 = calendar1.get(Calendar.HOUR);
int minute1 = calendar1.get(Calendar.MINUTE);
int second1 = calendar1.get(Calendar.SECOND);
/**
* 用自定义的calendar1给calendar赋值,
* 默认为"+"
* 前面带"-"为减去
*/
//加上多长小时
calendar.add(Calendar.HOUR, hour1);
//减去多长分钟
calendar.add(Calendar.MINUTE, -minute1);
//加上多长秒
calendar.add(Calendar.SECOND, +second1);
System.out.println("===========================");
System.out.println(sdf.format(calendar.getTime()));
}
}
下面是输出结果
上一篇: DLL