《工具类》得到前day天的所有日期

2021-04-02 09:51:53 浏览数 (1)

1.代码

代码语言:javascript复制
package com.css.app.base.org.action;

import com.css.restclient.inter.ISysClient;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class TestDemo{
    //得到前days天的所有日期
    public static void main(String[] args) {
        getAllDays(3);
    }
    
    public static void getAllDays(int days){
        //前天的时间戳
        Calendar start = Calendar.getInstance();
        start.setTime(getDateAdd(days));
        long timeInMillis = start.getTimeInMillis();
        //今天的时间戳
        long nowTime = System.currentTimeMillis();
        long oneDay = 1000*60*60*24;

        for (long i = 1; (nowTime - oneDay*i) >= timeInMillis; i  ) {
            long time1 = nowTime - oneDay*i;
            Date date = new Date(time1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            System.out.println(simpleDateFormat.format(date));
        }
    }

    /**
     * 将日期转换为时间戳
     * @param time
     * @return
     */
    public static String getStringTimestamp(String time) {
        String timestamp = null;

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Long longTime = sdf.parse(time).getTime();
            timestamp = Long.toString(longTime);

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

    /**
     * 得到前day天的日期
     * @param days
     * @return
     */
    private static Date getDateAdd(int days){
        // 使用默认时区和区域设置获取日历
        Calendar c = Calendar.getInstance();
        //得到day天前的日期
        c.add(Calendar.DAY_OF_MONTH, -days);
        return c.getTime();
    }
}

0 人点赞