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));

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM