查看@Basil Bourque 的最新答案
例如,如果我有一个“日期”变量“date1”,其值为 (dd/mm/yyy) 03/07/2011,这是星期日。如何获取前一个星期日“date2”的“日期”?其值为 (dd/mm/yyyy) 26/06/2011。
有没有简单的方法,例如:
伪代码:
Date date1 = (03/07/2011);
Date date2 = date1.subtractNumberOfDays(7);
最佳答案
你应该使用日历:
Calendar date = new GregorianCalendar(2011, Calendar.JULY, 3);
date.add(Calendar.DAY_OF_MONTH, -7);
System.out.println(date.getTime());
您也可以根据日期创建日历:
Date date1 = new Date(111, Calendar.JULY, 3);//the year field adds 1900 on to it.
Calendar date = new GregorianCalendar();
date.setTime(date1);
date.add(Calendar.DAY_OF_MONTH, -7);
date2 = date.getTime();
请注意:
- Java 用 0 代表一月!
- 日期(年、月、日)自 JDK 1.1 版起已弃用!
请参阅 GregorianCalendar JavaDoc:
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale. Parameters: year the value used to set the YEAR calendar field in the calendar. month the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January. dayOfMonth the value used to set the DAY_OF_MONTH calendar field in the calendar.
关于java - 如果我有一天的特定日期,我如何获得前一周的那一天的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6545935/