JAVA 獲取今天,7天前,一個月前,今年起始日期,同比日期

一介書生187發表於2020-12-01

今天的起始日期

 public static String getNowDateStart() {
        	long current=System.currentTimeMillis();    //當前時間毫秒數
            long zeroT=current/(1000*3600*24)*(1000*3600*24)- TimeZone.getDefault().getRawOffset();  //今天零點零分零秒的毫秒數
            String zero = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(zeroT);
            long endT=zeroT+24*60*60*1000-1;  //今天23點59分59秒的毫秒數
            String end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endT);
           System.out.println("今天開始時間:"+zero+",今天結束時間"+end);
            return null;
    }

幾天前(傳多少天都可以,7天,30天,365天都可以)

    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

今天的起始日期

    public static String getThisYear() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date time = new Date();
        try {
            Calendar currCal=Calendar.getInstance();
            Calendar calendar = Calendar.getInstance();
            calendar.clear();
            calendar.set(Calendar.YEAR,currCal.get(Calendar.YEAR));
            time = calendar.getTime();
        }catch (Exception e){
            e.printStackTrace();
        }
        return format.format(time);
    }

去年的起始日期

    public static String getUpYear() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date time = new Date();
        try {
            Calendar currCal=Calendar.getInstance();
            Calendar calendar = Calendar.getInstance();
            calendar.clear();
            calendar.set(Calendar.YEAR,currCal.get(Calendar.YEAR)-1);
            time = calendar.getTime();
        }catch (Exception e){
            e.printStackTrace();
        }
        return format.format(time);
    }

今年是哪年

    //獲取今年是哪年
    public static String getSysYear() {
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        return year;
    }

去年是哪年

    //獲取去年是哪年
    public static String getUpYearDate() {
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR)-1);
        return year;
    }

相關文章