Heim  >  Fragen und Antworten  >  Hauptteil

java - 求现在的时间减去30天后的时间

我要获取最近30天的东西,endDate就是现在的时间,startDate是现在的时间减去30天,求startDate是怎么做的??????谢谢
String endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String startDate = "";

PHPzPHPz2764 Tage vor886

Antworte allen(6)Ich werde antworten

  • PHPz

    PHPz2017-04-17 17:10:12

    如果不能使用java8,建议使用Calendar类来做,代码如下,add方法第二个参数传递负值即可。

            Calendar now = Calendar.getInstance();
            now.add(Calendar.DAY_OF_MONTH, -30);
            String endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now.getTime());
            System.out.println(endDate);
    

    java8版本可以使用下面的方法:

            LocalDateTime now = LocalDateTime.now();
            now = now.minus(30, ChronoUnit.DAYS);
            System.out.println(now.toString());

    Antwort
    0
  • 巴扎黑

    巴扎黑2017-04-17 17:10:12

    如下,最后格式根据需要转化下即可:

    var startDate = new Date( new Date() - 24*60*60*1000 * 30 );
    console.log('startDate: ' + startDate);
    // startDate: Tue Jan 19 2016 15:42:19 GMT+0800 (CST)

    Antwort
    0
  • 迷茫

    迷茫2017-04-17 17:10:12

    startDate = nowDate - 30 * 24 * 60 * 60 * 1000

    现在时间减去三十天的毫秒数即可。

    Antwort
    0
  • 迷茫

    迷茫2017-04-17 17:10:12

    Date endDate = new Date();
    Date startDate = new Date(endDate.getTime() - 30 * 24 * 60 * 60 * 1000);

    Antwort
    0
  • 怪我咯

    怪我咯2017-04-17 17:10:12

    public class Test {
        public static void main(String[] args) {
            Date endDate = new Date();
            Date startDate = getDateBefore(new Date(),30);
        }
    
        private static Date getDateBefore(Date d, int day){
            Calendar now =Calendar.getInstance();
            now.setTime(d);
            now.set(Calendar.DATE,now.get(Calendar.DATE)-day);
            return now.getTime();
        }
    }
    

    Antwort
    0
  • ringa_lee

    ringa_lee2017-04-17 17:10:12

    import org.apache.commons.lang3.time.DateUtils;
    
    Date now = new Date();
    Date startDate = DateUtils.addDays(now, -30);

    Antwort
    0
  • StornierenAntwort