JAVA获取某年(当年)的第一天的开始时刻和某年(当年)的最后一天的最后时刻

 

 

 

复制代码
package com.date;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Test {


    public static SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    public static SimpleDateFormat format1 = new SimpleDateFormat(
            "yyyyMMdd HH:mm:ss");

    /**
     * 得到指定日期的一天的的最后时刻23:59:59
     *
     * @param date
     * @return
     */
    public static Date getFinallyDate(Date date) {
        String temp = format.format(date);
        temp += " 23:59:59";

        try {
            return format1.parse(temp);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 得到指定日期的一天的开始时刻00:00:00
     *
     * @param date
     * @return
     */
    public static Date getStartDate(Date date) {
        String temp = format.format(date);
        temp += " 00:00:00";

        try {
            return format1.parse(temp);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取某年第一天日期开始时刻
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirstDay(int year){
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, year);
        Date yearFirstDay = cal.getTime();
        return getStartDate(yearFirstDay);
    }

    /**
     * 获取某年最后一天日期最后时刻
     * @param year 年份
     * @return Date
     */
    public static Date getYearLastDay(int year){
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, year);
        cal.roll(Calendar.DAY_OF_YEAR, -1);
        Date yearLastDay = cal.getTime();
        return getFinallyDate(yearLastDay);
    }

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        //获取当前年份
        int year = cal.get(Calendar.YEAR);
        System.out.println(year);

        System.out.println(getYearFirstDay(year));
        System.out.println(getYearLastDay(year));

    }
}
复制代码

 

posted @   yvioo  阅读(3297)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示