java last sunday of a month [duplicate] - java

This question already has answers here:
Get Last Friday of Month in Java
(16 answers)
Closed 4 years ago.
I want to get the last sunday of any given month, and its working to a point however on some inputs if the sunday is the first day of next month it shows that date instead of the same month's last week. Here is what
public static String getLastSunday(int month, int year) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1);
if (leap(year)) {
cal.add(Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK) - 2));
} else {
cal.add(Calendar.DAY_OF_MONTH, -(cal.get(Calendar.DAY_OF_WEEK)%7 - 1));
}
return cal.getTime().toString().substring(0, 10);
}
calling the function as:
getLastSunday(10, 2015);
returns the output:
Sun Nov 01
Where did I go wrong? Also if it is the leap year, I am not sure if going from -1 to -2 is correct, I researched about it but couldnt find anything useful.

tl;dr
YearMonth.of( 2015 , Month.NOVEMBER ) // Represent the entirety of a specified month.
.atEndOfMonth() // Get the date of the last day of that month.
.with( TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) ) // Move to the previous Sunday, or keep if already Sunday.
Avoid legacy date-time classes
The Question and other Answers are outmoded, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Use smart objects, not dumb primitives
Rather than pass year and month as mere integers, pass a single argument of YearMonth class. Doing so ensures valid values, makes your code more self-documenting, and provides type-safety.
YearMonth ym = YearMonth.of( 2015 , Month.NOVEMBER ) ; // Or YearMonth.of( 2015 , 11 ) with sane numbering for month 1-12 for January-December.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Get the last day of the month.
LocalDate endOfMonth = ym.atEndOfMonth() ;
Find the previous Sunday, or keep the end-of-month if it is already a Sunday. Use a TemporalAdjuster found in the TemporalAdjusters class.
LocalDate lastSundayOfPriorMonth = endOfMonth.with( TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) ) ;
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.

try this way
public static Date getLastSunday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month + 1, 1 );
cal.add(Calendar.DATE, -1);
cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) - 1 ) );
return cal.getTime();
}
source

Try this out (Remember Month value is 0-based. e.g., 0 for January)
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1);
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
cal.add(Calendar.DATE, -(cal.get(Calendar.DAY_OF_WEEK) -1));
return cal.getTime().toString().substring(0, 10);
So if you want to call this method for Oct 2015, then call like this:
getLastSunday(9, 2015);
Its doing the following things:
1. Setting the passed year and monthe to the calendar object
getLastSunday(9, 2015);
2. Then updates the calendar object to the last day of the current month by using this code:
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Then subtracts the number of days from the current date tot the last sunday:
JAVA sets 1 for SUNDAY , 2 for MONDAY and so on. So, if the last day is MONDAY i.e. 2 then it will subtract 1 from it to get the last sunday of the month.
Hope it helps.

Related

Get last day of specific(SEPTEMBER) month

How to get the fiscal year end date (2017-09-30) dynamically.
Based on the year I need to get the fiscal year end date dynamically.
For example:
If 2017 then output should be 2017-09-30
If 2018 then output should be 2018-09-30 and so on.
Code:
Calendar.getInstance().getActualMaximum(Calendar.SEPTEMBER);
Output I am getting as "4"
Can I know how to get the end date dynamically.
This will help you
private static String getDate(int month, int year) {
Calendar calendar = Calendar.getInstance();
// passing month-1 because 0-->jan, 1-->feb... 11-->dec
calendar.set(year, month - 1, 1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
Date date = calendar.getTime();
DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
return DATE_FORMAT.format(date);
}
Fiscal year?
The term “fiscal year” is not defined here. Usually that is a company-specific definition, and may not be as simple as “end of September”.
Avoid legacy date-time classes
If you are asking for the same month and same day-of-month but adjusted by year, use the java.time classes. The troublesome Calendar class is now legacy, and should be avoided.
LocalDate & MonthDay
The LocalDate class represents a date-only value without time-of-day and without time zone.
The MonthDay class represents a month and day-of-month without any year and without any time zone.
LocalDate ld = LocalDate.of( 2017 , Month.SEPTEMBER , 30 );
MonthDay md = MonthDay.from( ld );
LocalDate ldInAnotherYear = md.atYear( ld.getYear() + 1 );
You could also simply add a year depending on the date in question and what your desired behavior is for handling the last days of a month since months have different lengths, and of course February has the issue of Leap Year.
LocalDate yearLater = LocalDate.of( 2017 , Month.SEPTEMBER , 30 ).plusYears( 1 );
YearMonth
You might find the YearMonth class handy. You can ask it for the last day of the month.
YearMonth ym = YearMonth( 2017 , Month.SEPTEMBER );
LocalDate endOfMonth = ym.atEndOfMonth();
I recommend using objects rather than mere integers. Consider passing around objects such as YearMonth, MonthDay, LocalDate, and Month where appropriate rather than numbers.
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.

AlarmManger doesn't work [duplicate]

This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Closed 2 years ago.
Calendar rightNow = Calendar.getInstance();
String month = String.valueOf(rightNow.get(Calendar.MONTH));
After the execution of the above snippet, month gets a value of 10 instead of 11. How come?
Months are indexed from 0 not 1 so 10 is November and 11 will be December.
They start from 0 - check the docs
As is clear by the many answers: the month starts with 0.
Here's a tip: you should be using SimpleDateFormat to get the String-representation of the month:
Calendar rightNow = Calendar.getInstance();
java.text.SimpleDateFormat df1 = new java.text.SimpleDateFormat("MM");
java.text.SimpleDateFormat df2 = new java.text.SimpleDateFormat("MMM");
java.text.SimpleDateFormat df3 = new java.text.SimpleDateFormat("MMMM");
System.out.println(df1.format(rightNow.getTime()));
System.out.println(df2.format(rightNow.getTime()));
System.out.println(df3.format(rightNow.getTime()));
Output:
11
Nov
November
Note: the output may vary, it is Locale-specific.
As several people have pointed out, months returned by the Calendar and Date classes in Java are indexed from 0 instead of 1. So 0 is January, and the current month, November, is 10.
You might wonder why this is the case. The origins lie with the POSIX standard functions ctime, gmtime and localtime, which accept or return a time_t structure with the following fields (from man 3 ctime):
int tm_mday; /* day of month (1 - 31) */
int tm_mon; /* month of year (0 - 11) */
int tm_year; /* year - 1900 */
This API was copied pretty much exactly into the Java Date class in Java 1.0, and from there mostly intact into the Calendar class in Java 1.1. Sun fixed the most glaring problem when they introduced Calendar – the fact that the year 2001 in the Gregorian calendar was represented by the value 101 in their Date class. But I'm not sure why they didn't change the day and month values to at least both be consistent in their indexing, either from zero or one. This inconsistency and related confusion still exists in Java (and C) to this day.
Months start from zero, like indexes for lists.
Therefore Jan = 0, Feb = 1, etc.
From the API:
The first month of the year is JANUARY
which is 0; the last depends on the
number of months in a year.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html
tl;dr
LocalDate.now() // Returns a date-only `LocalDate` object for the current month of the JVM’s current default time zone.
.getMonthValue() // Returns 1-12 for January-December.
Details
Other answers are correct but outdated.
The troublesome old date-time classes had many poor design choices and flaws. One was the zero-based counting of month numbers 0-11 rather than the obvious 1-12.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
Now in maintenance mode, the Joda-Time project also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
Months 1-12
In java.time the month number is indeed the expected 1-12 for January-December.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Time zone
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
int month = today.getMonthValue(); // Returns 1-12 as values.
If you want a date-time for a time zone, use ZonedDateTime object in the same way.
ZonedDateTime now = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
int month = now.getMonthValue(); // Returns 1-12 as values.
Convert legacy classes
If you have a GregorianCalendar object in hand, convert to ZonedDateTime using new toZonedDateTime method added to the old class. For more conversion info, see Convert java.util.Date to what “java.time” type?
ZonedDateTime zdt = myGregorianCalendar.toZonedDateTime();
int month = zdt.getMonthValue(); // Returns 1-12 as values.
Month enum
The java.time classes include the handy Month enum, by the way. Use instances of this class in your code rather than mere integers to make your code more self-documenting, provide type-safety, and ensure valid values.
Month month = today.getMonth(); // Returns an instant of `Month` rather than integer.
The Month enum offers useful methods such as generating a String with the localized name of the month.
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.
cal.get(Calendar.MONTH) + 1;
The above statement gives the exact number of the month. As get(Calendar.Month) returns month starting from 0, adding 1 to the result would give the correct output. And keep in mind to subtract 1 when setting the month.
cal.set(Calendar.MONTH, (8 - 1));
Or use the constant variables provided.
cal.set(Calendar.MONTH, Calendar.AUGUST);
It would be better to use
Calendar.JANUARY
which is zero ...

What is the best way to retrieve the dates for last Monday and Friday

I need to get the dates for Monday and Friday last week. To do this, i am getting the date of Monday this week and subtracting 7 days. This gives me the date for Monday last week.
To get the date for Friday i have to add 4. This confused me a bit because for some reason the first day of the week is Sunday as opposed to Monday here in the UK.
Anyway, here is how i am getting the dates.
// Get the dates for last MON & FRI
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.add(Calendar.DAY_OF_WEEK, -7);
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
// Get the date on Friday
cal.add(Calendar.DAY_OF_WEEK, 4);
cal.set(Calendar.HOUR_OF_DAY,23);
cal.set(Calendar.MINUTE,59);
cal.set(Calendar.SECOND,59);
cal.set(Calendar.MILLISECOND,0);
The above works but i am interested if there is anything wrong with the logic. I.e. will it work for Februarys, leap years etc.
Feel free to suggest a better solution/approach.
Thanks
tl;dr
get the dates for Monday and Friday last week
LocalDate // Represent a date only, without a time-of-day, and without a time zone or offset.
.now // Capture the current date as seen through the wall-clock time used by the people of a certain region (a time zone).
(
ZoneId.of( "America/Montreal" )
) // Returns a `LocalDate` object.
.with // Move to another date.
(
TemporalAdjusters.previous( DayOfWeek.MONDAY ) // Returns an implementation of the `TemporalAdjuster` interface.
) // Returns another `LocalDate` object, separate and distinct from our original `LocalDate` object. Per the immutable objects design pattern.
Avoid legacy date-time classes
The other Answers use the troublesome old legacy date-time classes now supplanted by the java.time questions.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( “America/Montreal” );
LocalDate today = LocalDate.now( z );
TemporalAdjuster
The TemporalAdjuster interface provides for adjustments to move from one date-time value to another. Find handy implementations in the TemporalAdjusters class (note the plural 's'). The previous adjuster finds any specified object from the DayOfWeek enum.
The Question does not exactly define “last week”. Last seven days? Standard Monday-Sunday period? Localized week, such as Sunday-Saturday in the United States? The week prior to today’s week or including today’s partial week?
I will assume the prior seven days were intended.
LocalDate previousMonday = today.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) ) ;
LocalDate previousFriday = today.with( TemporalAdjusters.previous( DayOfWeek.FRIDAY ) ) ;
By the way, if you want to consider the initial date if it happens to already be the desired day-of-week, use alternate TemporalAdjuster implementations: previousOrSame or nextOrSame.
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, 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.
Note: For Java 8 and above please take a look at Basil Bourque's answer (link).
Java 8 introduced a new time/date API which offers most of Joda-Time's functionality.
Joda-Time offers really nice methods for problems like that.
Getting the dates for Monday and Friday last week would look something like this using Joda Time:
DateTime today = DateTime.now();
DateTime sameDayLastWeek = today.minusWeeks(1);
DateTime mondayLastWeek = sameDayLastWeek.withDayOfWeek(DateTimeConstants.MONDAY);
DateTime fridayLastWeek = sameDayLastWeek.withDayOfWeek(DateTimeConstants.FRIDAY);
You can create DateTime objects from java.util.Date objects and vice versa so it is easy to use with Java dates.
Using the above code with the date
DateTime today = new DateTime("2012-09-30");
results in "2012-09-17" for Monday and "2012-09-21" for Friday, setting the date to
DateTime tomorrow = new DateTime("2012-10-01");
results in "2012-09-24" for Monday and "2012-09-28" for Friday.
You still have start of week set to sunday, which means that Calendar.MONDAY on a saturday is the monday before, while Calendar.MONDAY on a sunday is the next day.
What you need to do is (according to how you want it according to your comment above), to set the start of week to monday.
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.add(Calendar.DAY_OF_WEEK, -7);
...
Beyond that, and that the last second of friday isn't included in the range, your logic seems sound, and shouldn't have trouble with leap years/DST shifts etc.
The only thing I see wrong is that you are in fact testing the range Mo-Fr, and not, as stated, retrieving two specific days. It would be safer to test range Mo-Sa with exclusive upper bound.
You can use TemporalAdjusters to adjust the desired dates/days you are looking for.
Example:
LocalDate today = LocalDate.now();
LocalDate lastMonday = today.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
LocalDate lastFriday = today.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));

If I have a specific date of a day, how do I get the date of that day in the previous week?

SEE ANSWER FROM #Basil Bourque for most up to date answer
For example, if I have a "Date" variable "date1" with a value of (dd/mm/yyy) 03/07/2011, which is a Sunday. How do I get the "Date" of the previous Sunday "date2"? which would have the value (dd/mm/yyyy) 26/06/2011.
Is there an easy way of doing it, for example:
pseudo code:
Date date1 = (03/07/2011);
Date date2 = date1.subtractNumberOfDays(7);
You should use Calendar:
Calendar date = new GregorianCalendar(2011, Calendar.JULY, 3);
date.add(Calendar.DAY_OF_MONTH, -7);
System.out.println(date.getTime());
You can create a calendar from date too:
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();
Be aware that:
Java uses 0 to represent January !
Date(year, month, day) is deprecated since JDK version 1.1 !
See the 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.
tl;dr
LocalDate.of( 2011 , Month.JULY , 3 )
.minusWeeks( 1 )
2011-06-26
java.time
The Question and Answers use old outmoded date-time classes. Instead use the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate localDate = LocalDate.of( 2011 , Month.JULY , 3 );
Alternatively, pass an integer in second argument instead of the Month enum. Pass 1-12 for January-December.
Previous week
You can subtract a week from the date.
LocalDate weekPrior = localDate.minusWeeks( 1 );
See this code run live at IdeOne.com.
Previous day-of-week
If you want a specific day of the week, use a TemporalAdjuster.
Several such handy implementations provided in the TemporalAdjusters class (note the plural 's').
LocalDate priorTuesday = localDate.with( TemporalAdjusters.previous( DayOfWeek.TUESDAY ) ) ;
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.
A more clear approach:
Calendar date = new GregorianCalendar(2011, 1, 1);
date.add(Calendar.WEEK_OF_MONTH, -1);
System.out.println(date.getTime());
use either WEEK_OF_MONTH or WEEK_OF_YEAR
If you are willing to use Joda time it will be very easy.
An example:
DateTime toDay=new DateTime();
DateTime dateOfPreviousWeek=toDay.minusDays(7);
Another:
DateTime toDay = new DateTime(2011, 7, 1, 0, 0, 0, 0);
DateTime dateOfPreviousWeek = toDay.minusDays(7);
You can get java.util.Date from DateTime as:
Date javaDate=jodaDateTime.toDate();

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