Because a project needs to count nearly 1 weeks, nearly 1 months, nearly 6 months of data, so in the time of the plus and minus a lot of ways, and finally decided to use Java.util.Calendar
Java.util.Calendar, which provides a way to calculate the time,
Calendar.date: Representative Days
Calendar.wednesday: Number of weeks represented
Calendar.month: Number of months represented
Calendar.year: Number of years represented
The calculation method is as follows:
1, calculate the date of the last week, that is, the time period of the past 7 days, such as today 2015-07-21 , one weeks ago that is 2015-07-14
public static void Main (string[] args) {Calendar cal = Calendar.getinstance (); Cal.settime (new Date ()); Cal.add ( Calendar.date,-7); System.out.println (dateutils.date2string ("Yyyy-mm-dd", Cal.gettime ()));
Or:
Calendar cal = Calendar.getinstance (); Cal.settime (new Date ()); Cal.add (Calendar.wednesday,-1); System.out.println (dateutils.date2string ("Yyyy-mm-dd", Cal.gettime ()));
The result of both is the result of 2015-07-14, but one is minus 7 days, one minus one weeks
Note: If you are calculating a future date, just remove the minus sign in front of the number.
2, calculate the date of the last one months, that is, the time period of the past one months, as follows:
Calendar cal = Calendar.getinstance (); Cal.settime (new Date ()); Cal.add (Calendar.month,-1); System.out.println (dateutils.date2string ("Yyyy-mm-dd", Cal.gettime ()));
Output Result: 2015-06-21
3. Calculate the date of the last year, that is, the time period of the past year, as follows:
Calendar cal = Calendar.getinstance (); Cal.settime (new Date ()); Cal.add (Calendar.year,-1); System.out.println (dateutils.date2string ("Yyyy-mm-dd", Cal.gettime ()));
Output Result: 2014-07-21
This calendar is very useful to calculate the start and end of the time period is very convenient ~
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java date Plus and minus days, months, years calculation method