Get Only Weekdays using Java - java

I have a requirement like when I insert values into a table in my DB, I need to set target dates which is 3 months apart from the day it was inserted. For Eg: If I insert data on 9th November 2013, My target dates will be 9th Feb 2014, 9th May 2015 and so on. Am storing these target dates in respective columns as well. For this am using Calendar function and adding 3 months to the current instance. Now business does not want my target dates to come on a saturday or Sunday. If it comes, I need to add the required days so that it comes on a weekday.
Any suggestions on how we can do it

Start from what you already know. You know you can use a Calendar to add/subtract values to/from and generate a resulting value....
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.DATE, 9);
cal.set(Calendar.MONTH, Calendar.NOVEMBER);
cal.set(Calendar.YEAR, 2013);
System.out.println("Start at " + cal.getTime());
cal.add(Calendar.MONTH, 3);
System.out.println("End at " + cal.getTime());
Which outputs...
Start at Sat Nov 09 00:00:00 EST 2013
End at Sun Feb 09 00:00:00 EST 2014
Now, you need to use this concept to move the day till it's not a week end. You can get the "day" name using Calendar.DAY_OF_WEEK and simply either add or subtract a day to the Calendar.DATE based on your business rules, for example...
while (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
cal.add(Calendar.DATE, 1);
}
System.out.println("Should end at " + cal.getTime());
Which will (based on the previous example), output...
Should end at Mon Feb 10 00:00:00 EST 2014
Take a closer look at Calendar for more details

java.time
The modern approach uses the java.time classes, extended by the ThreeTen-Extra project.
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate start = LocalDate.of( 2013 , Month.NOVEMBER , 9 ) ;
Step back one day, then ask for the next working day (non-Saturday/Sunday) by using an implementation of TemporalAdjuster found in org.threeten.extra.Temporals.
LocalDate startAgain =
start.minusDays( 1 )
.with( org.threeten.extra.Temporals.nextWorkingDay() ) ;
Add three months for next date. Again, step back a day and ask for next working day.
LocalDate threeMonthsLaterWorkingDay =
startAgain.plusMonths( 3 )
.minusDays( 1 )
.with( org.threeten.extra.Temporals.nextWorkingDay() ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

Java current date minus 3 months and start from month begining [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I need to get statistics for a quarter.
Example: today is February 10th 2018, I need to retrieve data from December 2017, from 1st to 31st, then from January 2018, from 1st to 30th and from February 1st to current date.
How can I achieve this using Java Date?
tl;dr
YearMonth.now().minusMonths( 1 ).atEndOfMonth() // or .atDay( 1 )
Details
Get today’s date.
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
LocalDate today = LocalDate.now( z ) ;
Get the year-month of that date.
YearMonth ymCurrent = YearMonth.from( today ) ;
Add the ThreeTen-Extra library to your project to access the LocalDateRange class. This class represents as one object a pair of LocalDate objects, start date and stop date, for a date range from one date to the other date.
LocalDateRange rangeCurrent = LocalDateRange.ofClosed( ymCurrent.atDay( 1 ) , today ) ;
Move to previous month.
YearMonth ymPrevious = ymCurrent.minusMonths( 1 ) ;
LocalDateRange rangePrevious = LocalDateRange.ofClosed( ymPrevious.atDay( 1 ) , ymPrevious.atEndOfMonth() ) ;
Subtract yet another time for your third month.
Tip: Consider using the Half-Open approach to defining a span of time, where the beginning is inclusive while the ending is exclusive. So a month starts with the first day of the month and runs up to, but does not include, the first day of the following month.
For another valid approach using java.time classes, see the Answer by diston.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Try something like this:
// Get current date
Calendar start;
start = Calendar.getInstance();
// Go to beginning of month
start.set(Calendar.DAY_OF_MONTH, 1);
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);
// Go 2 months back
my_date.add(Calendar.MONTH, -2);
// Get end of same month
Calendar end;
end = start.clone();
end.add(Calendar.MONTH, 1);
end.add(Calendar.DAY_OF_MONTH, -1);
Then, do something similar for the other months
You can use Java 8's java.time classes (or threeten backport for Java <= 7).
If you'll work only with day/month/year and don't care about hours and timezones, the best class to use is LocalDate. To create a specific date is easy:
// February 10th 2018
LocalDate current = LocalDate.of(2018, 2, 10);
Or you can call LocalDate.now() to get the current date.
Then, to get to December 1st 2017, you must subtract 2 months (2 months before February is December) and set the day to 1:
// start is December 1st 2017
LocalDate start = current
// 2 months ago = December
.minusMonths(2)
// change day of month to 1st
.withDayOfMonth(1);
Then you can loop from December 1st to February 10th:
LocalDate date = start;
while (date.isBefore(current)) {
// do whatever you need with the date
// go to the next day
date = date.plusDays(1);
}
Note that plusDays returns a new object, so I must assign it to the same variable, otherwise it won't be changed.
I also used isBefore, which doesn't include the current date in the loop - it'll stop at February 9th. If you want to include February 10th, change the condition to if (! date.isAfter(current))

Setting values in calendar (java.util.Calendar)

I'm learning the Calendar class in Java and I am unable to understand the Set(Calendar.Day OF MONTH) method.
Here it goes:
import java.util.Calendar;
import java.util.Date
public class TestCalender
{
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();
Date date= cal.getTime();
System.out.println(date);
cal.set(Calendar.DAY_OF_MONTH,33);
//cal.set(Calendar.MONTH,13);------>(1)
Date newdate = cal.getTime();
System.out.println(newdate);
Output:
Fri May 12 17:30:50 CDT 2017
Fri Jun 02 17:30:50 CDT 2017
When I uncomment the statement(1) the output changes to:
Fri May 12 17:33:22 CDT 2017
Mon Mar 05 17:33:22 CST 2018
Here is my question:
I understood the change of Month to March but I'm not able to figure out why the date has changed to 5. As per my understanding shouldn't the date be changed to April 02 2018 (when 33 days of March is being computed since March has only 31 days the count moves to the month of April).
I will be extremely grateful if someone could help in clearing this doubt.
Thanks in advance.
Regards
Roopa
The Calendar class uses months starting from 0, and ending at 11 for December. Therefore, when you set the month to 13, you specified February of the following year, and the "33rd day of February" (which has 28 days) is the 5th of March.
The java.util.date classes are quirky and hard to use. Use java.time instead.
I'm learning the Calendar class
Don't.
The Calendar class is notoriously troublesome, poorly designed, confusing, and flawed. Now legacy. Supplanted by the java.time classes. We can sweep that class into the dustbin of Java history.
Among its many issues, Calendar uses crazy month numbering 0-11 for January-December. This fact was correctly described in the correct Answer by Kyriacou. The java.time classes, in contrast, use sane numbering 1-12 for Jan-Dec; see the Month enum.
Not quite sure what your goal is in that code snippet, but you seem to be adding 33 days to a date.
The LocalDate class represents a date-only value without time-of-day and without time zone.
One big difference between java.time and the legacy classes is that the modern classes use immutable objects. So adding days to a date results in a new date object with its values based on the original object, while the original object remains untouched. This avoids much confusion, and makes them thread-safe.
LocalDate ld = LocalDate.of( 2017 , Month.MARCH , 23 ) ;
LocalDate later = ld.plusDays( 33 );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Calendar get year returns wrong result

I want to create a calendar object and set it to a certain year and a week in that year.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, weekOfYear); // 1
calendar.set(Calendar.YEAR, year); // 2016
setWeekChecked(calendar);
This is the toString of the calendar object as I pass it to the setWeekChecked method:
java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=America/New_York,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=0,WEEK_OF_YEAR=1,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=7,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=5,HOUR_OF_DAY=5,MINUTE=25,SECOND=43,MILLISECOND=219,ZONE_OFFSET=-18000000,DST_OFFSET=0]
In the setWeekChecked method:
public void setWeekChecked(final Calendar cal) {
final int targetWeek = cal.get(Calendar.WEEK_OF_YEAR); // Returns 1
final int targetYear = cal.get(Calendar.YEAR); // Returns 2015??
}
This is the toString of the calendar object now:
java.util.GregorianCalendar[time=1451557543219,areFieldsSet=true,lenient=true,zone=America/New_York,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=11,WEEK_OF_YEAR=1,WEEK_OF_MONTH=5,DAY_OF_MONTH=31,DAY_OF_YEAR=365,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=5,AM_PM=0,HOUR=5,HOUR_OF_DAY=5,MINUTE=25,SECOND=43,MILLISECOND=219,ZONE_OFFSET=-18000000,DST_OFFSET=0]
What am I doing wrong?
I suspect that the calendar is trying to use the current day-of-week (it's Thursday today) in the first week of 2016.
Now, looking at your calendar settings, you've got firstDayOfWeek=1 (so weeks run Sunday to Saturday) and minimalDaysInFirstWeek=1 (so the first week of the year is the one that includes January 1st).
That means that the first week of 2016 in your calendar ran from Decemember 27th 2015 to January 2nd 2016. Therefore Thursday in the first week was December 31st - which is exactly what the calendar you've shown us says.
Fundamentally, calendar arithmetic with "week of year" is tricky because:
There are lots of different culture-specific ways of looking at them
Typically requirements don't specify which of those you're actually interested in
I'd strongly recommend using Joda Time if at all possible to make your date/time-handling code clearer to start with, but you'll still need to work out exactly what you mean by "set it to a certain year and a week in that year". Note that Joda Time separates the concepts of "week-year" (used with week-of-week-year and day-of-week) from "year" (used with month and day-of-month) which helps greatly. You need to be aware that for a given date, the week-year and year may be different.
tl;dr
LocalDate.of( 2016 , Month.JULY , 1 )
.with( IsoFields.WEEK_OF_WEEK_BASED_YEAR , 1 )
Details
The Answer by Jon Skeet is correct. Update: We have a better way.
The java.time classes built into Java 8 and later supplant the troublesome old legacy date-time classes bundled with the earliest versions of Java. And java.time officially supplants Joda-Time, as that project is now in maintenance mode.
As Skeet points out, there are different ways to define week-of-year.
The java.time classes provide support for the standard ISO 8601 definition of week-of-year. This definition is that week number 1 is the first week with a Thursday, and that week starts on a Monday. So the beginning of the week may include one or more days of the previous year, and the last week may include one or more days from the following year. The year always has either 52 or 53 weeks.
See my Answer to a similar Question for more details.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Get a date near the middle of the desired year. That desired year is a week-based year rather than a calendar year, so must avoid the very beginning or ending of the calendar year. In your case, you wanted week-based year of 2016.
LocalDate ld = LocalDate.of( 2016 , Month.JULY , 1 ) ;
Next we adjust that date into the desired week by using IsoFields.WEEK_OF_WEEK_BASED_YEAR.
LocalDate dayIn2016W01 = ld.with( IsoFields.WEEK_OF_WEEK_BASED_YEAR , 1 ) ;
If you want the first day of that week, use another TemporalAdjuster from the TemporalAdjusters class.
LocalDate firstDayOf2016W01 = dayIn2016W01.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) );
Tip: When Android becomes more capable, use the YearWeek class from the ThreeTen-Extra project.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

java Calendar setFirstDayOfWeek not working

Here is the real calendar now:
March 2015
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
And I get DAY_OF_WEEK of 2015/3/24 like this:
public class TestCalendar {
public static void main(String[] argvs){
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(2015,Calendar.MARCH,24);
System.out.println(cal.get(Calendar.DAY_OF_WEEK));
}
}
Since I have cal.setFirstDayOfWeek to MONDAY the result I expecting is 2, but Whatever day I set to the first day of week(have tried SUNDAY and others) .It kept show me the same result which is 3. So It seemed that firstDayOfWeek won't affect the result.
Have I do something wrong?
EDIT
I just figured and thanks to answers below, that this setFirstDayOfWeek will not affect the result of get(Calendar.DAY_OF_WEEK) nor get(Calendar.WEEK_OF_YEAR)
Then what is this method setFirstDayOfWeek() designed for?
I mean How can I told the program that I want 2015/3/29 be the last day of the 12th week instead of treating it as the first day of the 13th week?
tl;dr
LocalDate.of( 2015 , Month.MARCH , 24 ) // `LocalDate` object for 2015-03-24.
.getDayOfWeek() // DayOfWeek.TUESDAY constant object
.getValue() // 2
Avoid legacy date-time classes
Calendar is a ugly mess, as are its sibling classes. Fortunately these old date-time classes are now legacy, supplanted by the java.time classes.
ISO 8601
If you want Monday as the first day of the week, Sunday the last, numbered 1-7, then use the ISO 8601 calendar used by default in the java.time classes.
DayOfWeek
The DayOfWeek enum hold predefined objects for each of those ISO days of the week. You can interrogate for its number if need be, though generally better to pass around objects of this enum rather than mere integers.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2015 , Month.MARCH , 24 );
DayOfWeek dow = ld.getDayOfWeek();
int value = dow.getValue(); // 1-7 for Monday-Sunday. But often better to use the `DayOfWeek` object rather than a mere integer number.
For working with other definitions of a week where Monday is not day number one, see the WeekFields class.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
cal.get(Calendar.DAY_OF_WEEK) will return you which day it is (SUNDAY, MONDAY, etc...) for the given date. So it will return you TUESDAY and then 3, whatever the first day of week is. This has nothing to do with the setFirstDayOfWeek method.
If you want to compute the number of day since the beginning of the week, you just have to get the first day of the week using getFirstDayOfWeek and do some simple math.
setFirstDayOfWeek just tells the Calendar which day is to be considered the first day,i.e., Sunday or Monday or any other day. It will not change the dayOfWeek for any arbitrary date. The javadoc for this method states the following:
public void setFirstDayOfWeek(int value)
Sets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.
Parameters:
value - the given first day of the week.

How to set an expiration date in java

I am trying to write some code to correctly set an expiration date given a certain date.
For instance this is what i have.
Date lastSignupDate = m.getLastSignupDate();
long expirationDate = 0;
long milliseconds_in_half_year = 15778463000L;
expirationDate = lastSignupDate.getTime() + milliseconds_in_half_year;
Date newDate = new Date(expirationDate);
However, say if i the sign up date is on 5/7/2011 the expiration date output i get is on 11/6/2011 which is not exactly half of a year from the given date. Is there an easier way to do this?
I would use the Calendar class - the add method will do this kind of thing perfectly.
http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 6);
java.util.Date expirationDate = cal.getTime();
System.err.println(expirationDate);
Here's a simple suggestion using joda-time:
DateTime dt = new DateTime(lastSignupDate);
dt = dt.plusDays(DateTimeConstants.MILLIS_PER_DAY * 365 / 2);
// you can also use dt.plusDays(364 / 2);
You can also use a Calendar:
Calendar c = Calendar.getInstance();
c.setTime(lastSignupDate);
c.add(Calendar.MILLISECOND, MILLIS_PER_DAY * 365 / 2);
// or c.add(Calendar.DAY_OF_YEAR, 364 / 2);
tl;dr
java.time.LocalDate.of( 2011 , Month.MAY , 7 )
.plusMonths( 6 )
.toString()
2011-11-07
java.time
You are using date-time values, so you must account for issues such as time zones, anomalies, and leap year. But you only want a date without a time-of-day and without a time zone, so much easier if you use a date-only class rather than a date-with-time class.
The modern approach uses java.time rather than the troublesome legacy date-time classes.
if i the sign up date is on 5/7/2011 the expiration date output i get is on 11/6/2011 which is not exactly half of a year from the given date
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2011 , Month.MAY , 7 ) ;
You can do math with the java.time classes. Look for plus… and minus… methods.
LocalDate sixMonthsLater = ld.plusMonths( 6 ) ;
Or pass the amount of time.
Period p = Period.ofMonths( 6 ) ;
LocalDate sixMonthsLater = ld.plus( p ) ;
See this code run live at IdeOne.com.
2011-05-07
2011-11-07
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Do you really need an expiration-date, which is accurate to the millisecond?
I would implement it as 6 Months from x.
Jan. 1 => Jul 1
Sep. 28=> Feb 28
Sep. 29=> Feb 28
Sep. 30=> Feb 28
Oct. 1=> Mar 1
Maybe you like to be generous, and say 'Mar 1' for 'Sep 29 and 30' too.
Here's an example of using Date with TimeUnit that's a little more readable:
long year = TimeUnit.MILLISECONDS.convert(365, TimeUnit.DAYS);
Date expiry = new Date(System.currentTimeMillis() + year);
System.out.println(expiry);
Shame it doesn't have year and day, look at GregorianCalendar or Jodatime for a better API.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(new Date().getTime());
// 10 minutes expiration time
calendar.add(calendar.MINUTE, 10);
// prints 10 minutes ahead time
System.out.println(new Date(calendar.getTime().getTime()));

Categories