java时间运算

2021-03-06  本文已影响0人  c之气三段
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class Time {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = ft.parse("1900-01-01 00:00:00");
        Date endTime = ft.parse("2050-01-01 00:00:00");
        System.out.println("请输入时间点(格式为yyyy-MM-dd hh:mm:ss):");
        Scanner scanner=new Scanner(System.in);
        String time= scanner.nextLine();
        Date input = ft.parse(time);
        boolean effectiveDate = isEffectiveDate(input, startTime, endTime);
        if (effectiveDate) {
            System.out.println("输入时间在范围内");
            nextTime(input,ft);
        } else {
            System.out.println("输入时间在不在范围内");
        }
    }
   //判断输入的时间是否在设置的时间内
    public static boolean isEffectiveDate(Date input, Date startTime, Date endTime) {
        if (input.getTime() == startTime.getTime()
                || input.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(input);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }
//输入时间3小时后的工作时间点,有休息时间就跳过
    public static void nextTime( Date input, SimpleDateFormat ft){
        Calendar that = Calendar.getInstance();
        int nextTime=3;
        int noonRest=2;
        that.setTime(input);
        int thatOur=Integer.parseInt(ft.format(that.getTime()).substring(11,13));//取出小时
        if((thatOur<=9&&thatOur>=8)||(thatOur>=14&&thatOur<=15)){that.add(Calendar.HOUR,nextTime);}//不跳过休息时间
        else if(thatOur<8)that.add(Calendar.HOUR,11-thatOur);//早上8点之前,直接跳到11点后
        else if(thatOur<12)that.add(Calendar.HOUR,nextTime+noonRest);//12点之前,且会跳过休息时间
        else if(thatOur<14)that.add(Calendar.HOUR,17-thatOur);//午间休息时间点,直接跳到17点后
        else that.add(Calendar.HOUR,24-thatOur+11);//晚上下班后,直接跳到第二天11点后
        System.out.println("增加3小时(跳过休息时间):"+ft.format(that.getTime()));
    }
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//获取当前时间
public class Time {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(ft.format(new Date()));
    }


}
上一篇 下一篇

猜你喜欢

热点阅读