store current date and date 1 year from current in java - java

I have everything setup already to store the current date to a variable in Java. What I am trying to figure out is how to store a date of 1 year after the current date.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Scanner;
import java.util.Calendar;
Here is what I have for the current date:
DateFormat newDate = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
startDate = newDate.format(date);
So if it were today for example it would store 2/18/2013. I am trying to store the date 2/18/2014. How would I go about doing this?

If you do not want to drag external libraries, just use calendar.add(Calendar.YEAR, 1)
Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
cal.add(Calendar.YEAR, 1); // to get previous year add -1
Date nextYear = cal.getTime();
Note, if the date was 29/Feb/2012 and you added 1 year, you will get 28/Feb/2013

tl;dr
LocalDate.parse(
"2/18/2013" ,
DateTimeFormatter.ofPattern ( "M/d/uuuu" )
).plusYears( 1 )
Details
The accepted Answer is correct, but outdated as of Java 8.
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
LocalDate
These new classes include LocalDate, to represent a date-only value with no time-of-day nor time zone.
First we must parse the String input. The java.time formatter uses pattern codes similar to the old classes, but not exactly the same. So be sure to read the new doc carefully.
Padded Zero
Notice that your input String lacks leading zero digit for some values. That means you should use single pattern codes, M and d rather than MM and dd. Double codes means you expect padding zero to always be included for otherwise single-digit values, 02 rather than 2.
String input = "2/18/2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "M/d/uuuu" );
LocalDate localDate = LocalDate.parse ( input , formatter );
Add a year. The java.time framework takes care of leap year.
LocalDate yearLater = localDate.plusYears ( 1 );
Dump to console.
System.out.println ( "localDate: " + localDate + " and yearLater: " + yearLater );
localDate: 2013-02-18 and yearLater: 2014-02-18
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, Java SE 11, and later - 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
Most 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.

Use Calendar#add(int field, int amount) method.You should use Calendar API in-order to manipulate date and time operations.
Calendar today = Calendar.getInstance();
Calendar nextYearToday = today;
nextYearToday.add(Calendar.YEAR, 1);

Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
cal.add(Calendar.YEAR, 1); // to get previous year add 1
cal.add(Calendar.DAY_OF_MONTH, -1); // to get previous day add -1
Date expiryDate = cal.getTime();
System.out.println("today is --> "+today);
System.out.println("expiryDate is --> "+expiryDate);
OutPut
today is --> Fri Dec 01 10:10:52 GMT+05:30 2017
expiryDate is --> Fri Nov 30 10:10:52 GMT+05:30 2018
date today is -> Fri Dec 01 10:10:52 GMT+05:30 2017
expiryDate is -> Fri Nov 30 10:10:52 GMT+05:30 2018

In Android is simpler than ever:
oneYearAfterDate = new Date(date.getTime() + DateUtils.YEAR_IN_MILLIS )

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.

Using an offset for a date that isn't today

I did a lot of searches trying to find this solution. Messing with dates in Java gives me a headache. Most of the results I found were using math to find a previous date or about finding a date offset from today's date. I really needed something from a predefined date (not today). I messed with a lot of classes and code before finding what I needed.
This is also my first post here. I'm a veteran lurker. I hope this saves someone the time I took to find this.
Submit date Dec 2, 2014 and find the date from the week before.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class FilenameDateFormat {
SimpleDateFormat fileDateFormat = new SimpleDateFormat("yyyyMMdd");
public static void main(String[] args) throws ParseException {
new FilenameDateFormat("20141202", -7);
}
public FilenameDateFormat(String dateArg, int offsetDays) throws ParseException {
Date fileDate = fileDateFormat.parse(dateArg);
Calendar cal = new GregorianCalendar();
cal.setTime(fileDate);
cal.add(Calendar.DAY_OF_MONTH, offsetDays);
System.out.println(cal.getTime());
}
}
RESULT
Tue Nov 25 00:00:00 EST 2014
Why dont you use new java.time api ? This could be easily acomplished in java8.
https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
tl;dr
LocalDate.parse(
"20141202" ,
DateTimeFormatter.BASIC_ISO_DATE
).minusWeeks( 1 )
2014-11-25
Avoid legacy date-time classes
Messing with dates in Java gives me a headache.
Date-time work in general is tricky, slippery, elusive.
And using the troublesome old date-time classes (java.util.Date, java.util.Calendar, etc.) makes the work all the more difficult. Those old classes are now legacy, supplanted by the java.time classes.
LocalDate
Submit date Dec 2, 2014
The LocalDate class represents a date-only value without time-of-day and without time zone.
Your input string happens to be in the “basic” version of the standard ISO 8601 format. The canonical version includes hyphens, 2014-12-02, while the “basic” version minimizes the use of separators, 20141202. I strongly suggest using the fuller version when possible to improve readability and reduce ambiguity/confusion.
DateTimeFormatter
The DateTimeFormatter class includes a pre-defined formatting pattern for your input, DateTimeFormatter.BASIC_ISO_DATE.
String input = "20141202" ;
DateTimeFormatter f = DateTimeFormatter.BASIC_ISO_DATE ;
LocalDate ld = LocalDate.parse( input , f );
In real code, trap for the DateTimeParseException being thrown because of bad input.
String input = "20141202" ;
DateTimeFormatter f = DateTimeFormatter.BASIC_ISO_DATE ;
LocalDate ld = null;
try{
ld = LocalDate.parse( input , f );
} catch ( DateTimeParseException e ) {
… // Handle error because of bad input.
}
Subtracting a week
find the date from the week before
Subtract a week. Note that java.time uses immutable objects. So rather than alter (mutate) the values in an object, we generate a new and separate object based on the original’s values.
LocalDate oneWeekAgo = ld.minusWeeks( 1 );
input: 20141202
ld.toString(): 2014-12-02
oneWeekAgo.toString(): 2014-11-25
See live code in IdeOne.com.
If you want a String in the same format as the input, use the same formatter seen above.
String output = oneWeekAgo.format( DateTimeFormatter.BASIC_ISO_DATE );
20141125
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.

Get Date in Java given Week number, week day and year

Given Week of the year, the week day and the year, how can we get the Date in Java?
With Jodatime, I tried the following:
DateTime dt = new DateTime();
dt.withYear(year);
dt.withWeekOfWeekyear(weekOfYear);
dt.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
But it gets the current Date!
JodaTime returns a changed copy, so do:
DateTime dt = new DateTime()
.withWeekyear(year)
.withWeekOfWeekyear(weekOfYear)
.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
And this should work as expected.
The accepted answer has bug..withYear(year) should be withWeekyear(year). #Neet please update it.
You need to reassign the date afterwards!
the dt.with*() methods simply make a copy of the date.
try
DateTime dt = new DateTime();
dt = dt.withYear(year);
dt = dt.withWeekOfWeekyear(weekOfYear);
dt = dt.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
We can also use this native java code using Calendar class:
SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 23);
cal.set(Calendar.DAY_OF_WEEK, 3);
cal.set(Calendar.YEAR,2013);
System.out.println(sdf.format(cal.getTime()));
Here is a simple example of how to do it without JodaTime:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Snippet {
public static void main(String args[]) {
String year = "2013";
String week_of_year = "46";
String day_of_week = "4";
String yearweekday = year + week_of_year + day_of_week;
SimpleDateFormat sdf = new SimpleDateFormat("yyyywwu");
Date date = null;
try {
date = sdf.parse(yearweekday);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
}
}
Good luck!
tl;dr
YearWeek.of( 2017 , 1 )
.atDay( DayOfWeek.TUESDAY )
.format( DateTimeFormatter.ofPattern( "uuMMdd" ) )
“Week” ambiguous
The word 'week' is ambiguous. Do you mean week number 1 contains January 1? Or week number 1 contains the first of a particular day of year such as Sunday or Monday?
Or do you mean a standard ISO 8601 week? To quote from YearWeek doc:
ISO-8601 defines the week as always starting with Monday. The first week is the week which contains the first Thursday of the calendar year. As such, the week-based-year used in this class does not align with the calendar year.
java.time
The modern approach uses the java.time classes.
The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
ThreeTen-Extra
The ThreeTen-Extra project extends java.time with additional functionality. This includes a handy YearWeek class, just what we need for this Question.
Specify your week-based year number and your week number.
YearWeek yw = YearWeek.of( 2017 , 1 ) ;
The LocalDate class represents a date-only value without time-of-day and without time zone.
You can ask the YearWeek object to determine the date of a day contained within its week. Specify a DayOfWeek enum object. Note that a DayOfWeek is an object rather than a mere integer or string, providing for type-safety and valid values.
LocalDate ld = yw.atDay( 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.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
int weekNumber = 34;
int year = 2021;
System.out.println(getLocalDate(weekNumber, DayOfWeek.TUESDAY, year, Locale.UK));
System.out.println(getLocalDate(weekNumber, DayOfWeek.TUESDAY, year, Locale.US));
System.out.println(getLocalDate(weekNumber, DayOfWeek.SUNDAY, year, Locale.UK));
System.out.println(getLocalDate(weekNumber, DayOfWeek.SUNDAY, year, Locale.US));
}
static LocalDate getLocalDate(int weekNumber, DayOfWeek dow, int year, Locale locale) {
return LocalDate.of(year, 2, 1)
.with(dow)
.with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
}
}
Output:
2021-08-24
2021-08-17
2021-08-29
2021-08-15
ONLINE DEMO
Note that the first day of the week is Locale-dependent e.g. it is Monday in the UK while Sunday in the US. As per the ISO 8601 standards, it is Monday. For comparison, check the US calendar and the UK calendar. Accordingly, the date will vary as shown in the example above.
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Get Only Weekdays using 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.

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