java-时间日期常用操作

年月日获取

        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(dateFormat.format(date));

        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat1= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(dateFormat1.format(calendar.getTime()));


        Calendar cal=Calendar.getInstance();
        int y=cal.get(Calendar.YEAR);
        //m要加1才是当前的月份
        int m=cal.get(Calendar.MONTH);
        int d=cal.get(Calendar.DATE);
        int h=cal.get(Calendar.HOUR_OF_DAY);
        int mi=cal.get(Calendar.MINUTE);
        int s=cal.get(Calendar.SECOND);
        System.out.println("现在时刻是"+y+"年"+m+"月"+d+"日"+h+"时"+mi+"分"+s+"秒");

输出
2024-02-29 17:06:40
2024-02-29 17:06:40
现在时刻是2024年1月29日17时6分40秒

12小时制和二十四小时制

  //这里是12小时制
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        //这里注意要加1
        int day = cal.get(Calendar.DATE);
        int hour = cal.get(Calendar.HOUR);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        //二十四小时制
        cal.get(Calendar.HOUR_OF_DAY );//得到24小时机制的

一个小时以后的时间戳

    public static void main(String[] args) {

		//一个小时以后的时间戳
        System.out.println(afterOneHourToNowDate(new Date()).getTime());
        //当前时间戳
        System.out.println((new Date()).getTime());
    }

    public static Date afterOneHourToNowDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        /* HOUR_OF_DAY 指示一天中的小时 */
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY, 1);
        return calendar.getTime();
    }

增加15天后的时间

//增加15天
        Date d = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currdate = format.format(d);
        System.out.println("现在的日期是:" + currdate);

        Calendar ca = Calendar.getInstance();
        ca.setTime(d);
        ca.add(Calendar.DATE, 15);// num为增加的天数,可以改变的
        d = ca.getTime();
        String enddate = format.format(d);
        System.out.println("增加天数以后的日期:" + enddate);

英文时间字符串转时间

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = sdf.parse(timeStr);

中文时间转英文时间

        String chineseDate = "2023年06月24日 10时15分30秒";
        SimpleDateFormat chineseDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        Date date = chineseDateFormat.parse(chineseDate);
        SimpleDateFormat englishDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String englishDate = englishDateFormat.format(date);
        System.out.println(englishDate);
        
		2023-06-24 10:15:30

中文字符中正则匹配年月日

		String lastNote=“2023年4月25日胜多负少的放松点发送dfs地方是地方水电费是地方水电费”
        Pattern pattern = Pattern.compile("(\\d+)年(\\d+)月(\\d+)日");
        Matcher matcher = pattern.matcher(lastNote);

        String lastRecordDate="";
        if (matcher.find()) {
            int year = Integer.parseInt(matcher.group(1));
            int month = Integer.parseInt(matcher.group(2));
            int day = Integer.parseInt(matcher.group(3));
            System.out.println("年: " + year + ", 月: " + month + ", 日: " + day);
            lastRecordDate=year+"年"+month+"月"+day+"日";
        }

获取当前时间与过去时间的相差天数

    public static Long getDay(String date) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long days = null;
        try {
            Date currentTime = dateFormat.parse(dateFormat.format(new Date()));//现在系统当前时间
            Date pastTime = dateFormat.parse(date);//过去时间
            long diff = currentTime.getTime() - pastTime.getTime();
            days = diff / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

获取当前时间与未来时间的相差天数

    public static Long getDayAfter(String date) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long days = null;
        try {
            Date currentTime = dateFormat.parse(dateFormat.format(new Date()));//现在系统当前时间
            Date pastTime = dateFormat.parse(date);//过去时间
            long diff =  pastTime.getTime()-currentTime.getTime();
            days = diff / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

获取指定时间加多少分钟后与当前时间的差多少分钟

    public long getDiffMinute(String timeStr){
        long diffMinute=0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date d = sdf.parse(timeStr);
            Calendar ca = Calendar.getInstance();
            ca.setTime(d);
            ca.add(Calendar.MINUTE, 15);
            d = ca.getTime();

            String enddate = format.format(d);
            String timeStr1 = enddate;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime dateTime = LocalDateTime.parse(timeStr1, formatter);

            int year = dateTime.getYear();
            int month = dateTime.getMonthValue();
            int day = dateTime.getDayOfMonth();
            int hour = dateTime.getHour();
            int minute = dateTime.getMinute();
            int second = dateTime.getSecond();

            diffMinute=getMinnuteAfter(year, month, day, hour, minute);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return diffMinute;
    }

    public  long getMinnuteAfter(int year, int month, int day, int hour, int minute) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime futureTime = LocalDateTime.of(year, month, day, hour, minute);
        long minutesDiff = ChronoUnit.MINUTES.between(now, futureTime);
        return minutesDiff;
    }

判断当前时间是否在指定时间前或者后

            Calendar cal=Calendar.getInstance();
            int y=cal.get(Calendar.YEAR);
            int m=cal.get(Calendar.MONTH);
            int d=cal.get(Calendar.DATE);
            int h=cal.get(Calendar.HOUR_OF_DAY);
            int mi=cal.get(Calendar.MINUTE);
            int s=cal.get(Calendar.SECOND);
            System.out.println("现在时刻是"+y+"年"+(m+1)+"月"+d+"日"+h+"时"+mi+"分"+s+"秒");
            
            LocalDateTime specifiedTime = LocalDateTime.of(y, m+1, d, 18, 0);
            LocalDateTime specifiedTime830 = LocalDateTime.of(y, m+1, d, 20, 30);
            LocalDateTime currentTime = LocalDateTime.now();
            if(currentTime.equals(specifiedTime) || currentTime.equals(specifiedTime830)){
                System.out.println("6点或者8停止执行");
                System.exit(0);
            }

后去当前月第一天和上个月第一天

        LocalDate today = LocalDate.now(); // 获取当前日期
        YearMonth thisMonth = YearMonth.from(today); // 获取当前月份
        System.out.println(" 获取当前月份:"+thisMonth.format(DateTimeFormatter.ofPattern("yyyyMM")));

        // 获取上个月的第一天
        YearMonth firstDayOfLastMonth = thisMonth.minusMonths(1);

        // 获取当前月份的第一天
        LocalDate firstDayOfMonth = thisMonth.atDay(1);

        // 获取当前月份的最后一天
        LocalDate lastDayOfMonth = thisMonth.atDay(thisMonth.lengthOfMonth());

        System.out.println(" 上个月第一天: " + firstDayOfLastMonth.atDay(1).toString() + " 00:00:00");
        System.out.println(" 当前月的第一天:"+firstDayOfMonth.toString());
        System.out.println(" 当前月最后一天: " + lastDayOfMonth.toString() + " 00:00:00");
		
		输出
		 获取当前月份:202402
		 上个月第一天: 2024-01-01 00:00:00
		 当前月的第一天:2024-02-01
		 当前月最后一天: 2024-02-29 00:00:00

		如果要改变格式可用如下:
		LocalDateTime today = LocalDateTime.now();
        YearMonth yearmonth = YearMonth.from(today);
        
        YearMonth firstDayOfPreMonth = yearmonth.minusMonths(1);
        System.out.println(firstDayOfPreMonth.atDay(1).format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        
        LocalDate lastDayOfMonth = yearmonth.atDay(yearmonth.lengthOfMonth());
        System.out.println(lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
		
		输出
		20240101
		20240229

参考

https://blog.csdn.net/BASK2312/article/details/131419428 LocalDateTime

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值