简体   繁体   English

使用 java.util.Date 获取过去的日期

[英]Get date in past using java.util.Date

Below is code I am using to access the date in past, 10 days ago.下面是我用来访问过去 10 天前的日期的代码。 The output is '20130103' which is today's date.输出为“20130103”,即今天的日期。 How can I return todays date - 10 days ?我怎样才能返回今天的日期 - 10 天? I'm restricted to using the built in java date classes, so cannot use joda time.我只能使用内置的 java 日期类,所以不能使用 joda 时间。

package past.date;

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

public class PastDate {

    public static void main(String args[]){

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date myDate = new Date(System.currentTimeMillis());
        Date oneDayBefore = new Date(myDate.getTime() - 10);    
        String dateStr = dateFormat.format(oneDayBefore);      
        System.out.println("result is "+dateStr);

    }

}

you could manipulate a date with Calendar 's methods.您可以使用Calendar的方法操作日期。

DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = new Date(System.currentTimeMillis());
System.out.println("result is "+ dateFormat.format(myDate));
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.DATE, -10);
System.out.println(dateFormat.format(cal.getTime()));

This line这条线

Date oneDayBefore = new Date(myDate.getTime() - 10);    

sets the date back 10 milliseconds, not 10 days.将日期设置回 10 毫秒,而不是 10 天。 The easiest solution would be to just subtract the number of milliseconds in 10 days:最简单的解决方案是减去 10 天内的毫秒数:

Date tenDaysBefore = new Date(myDate.getTime() - (10 * 24 * 60 * 60 * 1000));    

使用Calendar.add(Calendar.DAY_OF_MONTH, -10)

The class Date represents a specific instant in time, with millisecond precision.类 Date 表示特定的时刻,精度为毫秒。

Date oneDayBefore = new Date(myDate.getTime() - 10); 

So here you subtract only 10 milliseconds, but you need to subtract 10 days by multiplying it by 10 * 24 * 60 * 60 * 1000所以这里你只减去10毫秒,但是你需要乘以10 * 24 * 60 * 60 * 1000减去10天

你也可以这样做:

Date tenDaysBefore = DateUtils.addDays(new Date(), -10);
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today30 = cal.getTime();
System.out.println(today30);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM