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()));
Related
I get from my GPS tracker a time String in UTC-Format like this: hhmmss.ssss.
I want to convert the UTC time to the local time of the user by using calendar. So I extract the hours, minutes and seconds from the time String via substring(int start, int end) and set it via the Calendar.set(int field, int value) function. After this I convert the Calendar to a Date, but know I have a wrong day.
For example timestamp = 091215.0000,
If I log Calendar.getInstance()I get: Thu Dec 11 10:12:15 GMT+01:00 2018
But when I convert it with my function I get: Thu Dec 13 10:12:15 GMT+01:00 2018
My function
public static Date utcToLocalTimeFromLock(String timestamp) {
Calendar calendar = Calendar.getInstance();
if (timestamp.charAt(0) == '0') {
calendar.set(Calendar.HOUR_OF_DAY, timestamp.charAt(1) + 1);
} else {
calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(timestamp.substring(0, 2) + 1));
}
calendar.set(Calendar.MINUTE, Integer.valueOf(timestamp.substring(2, 4)));
calendar.set(Calendar.SECOND, Integer.valueOf(timestamp.substring(4, 6)));
Date date = calendar.getTime();
Log.d(LOG_TAG, "utcToLocalTimeFromLock: " + date);
return date;
}
What went wrong in your code?
Your bug is in this line:
calendar.set(Calendar.HOUR_OF_DAY, timestamp.charAt(1) + 1);
Characters are represented as numbers in computers. It’s a confusing fact of Java that characters and numbers can be used interchangeably in many cases. If timestamp.charAt(1) is the char '9' as in your example, it is represented as the number 57. When you add 1, you get 58. When you set the hour of day to 58 — if you had expected the Calendar class with default settings to report an error, you were wrong, this a confusing thing about that class and just one of the many reasons why we recommend you avoid using it. It just keeps counting hours into the next days and coincidentally ends up at the right hour of day, 10, only two days later (two days is 48 hours, and 48 + 10 = 58).
Other recommendation:
Don’t “hand parse” your time string. Leave parsing to a library class.
Don’t convert to Central European Time by adding an hour. It’s error-prone. During summer time (DST) it will give an incorrect result. It’s not portable to other time zones. Instead again leave the conversion to the library classes.
How to fix?
Basil Bourque already showed the good way to solve your problem using java.time, the modern Java date and time API. I’d like to show you that with java.time you can also include the fraction of second without much trouble if you like, though.
static DateTimeFormatter timeFormatter = new DateTimeFormatterBuilder()
.appendPattern("HHmmss")
.appendFraction(ChronoField.NANO_OF_SECOND, 3, 4, true)
.toFormatter(Locale.ROOT);
static ZoneId zone = ZoneId.of("Europe/Paris");
public static ZonedDateTime utcToLocalTimeFromLock(String timestamp) {
return LocalDate.now(ZoneOffset.UTC)
.atTime(LocalTime.parse(timestamp, timeFormatter))
.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(zone);
}
Let’s try:
System.out.println(utcToLocalTimeFromLock(timestamp));
Output when running just now:
2018-12-11T10:12:15+01:00[Europe/Paris]
The appendFraction method takes a minimum and maximum number of decimals after the point, so I specified 3 and 4, respectively. Depending on your needs you may specify a minimum down to 0 and a maximum up to 9 digits.
Of course replace your own time zone if it didn’t happen to Europe/Paris.
If you indispensably need an old-fashioned Date object for a legacy API that you don’t want to upgrade just now:
public static Date utcToLocalTimeFromLock(String timestamp) {
Instant inst= LocalDate.now(ZoneOffset.UTC)
.atTime(LocalTime.parse(timestamp, timeFormatter))
.atOffset(ZoneOffset.UTC)
.toInstant();
return Date.from(inst);
}
Tue Dec 11 10:12:15 CET 2018
If using the backport (ThreeTen Backport and/or ThreeTenABP, see below) for conversion from Instant to Date instead of Date.from(inst) use this:
return DateTimeUtils.toDate(inst);
Because a Date doesn’t have a time zone, no time zone conversion is necessary in this case. Only because I happen to be in Central European Time zone too, does the output agree with what you expect — it will be the time in the JVM’s time zone.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
java.time
You are using terrible old date-time classes that were supplanted years ago by the industry-leading java.time classes.
Capture the current moment in UTC as an OffsetDateTime object.
OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC ) ;
Parse the time-of-day as a LocalTime.
String input = "091215.000" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "HHmmss.SSS" ) ;
LocalTime lt = LocalTime.parse( input ) ;
Apply our time of day.
OffsetDateTime odt = now.with( lt ) ;
You may have a problem near the stroke of midnight. You might want to add some code to see if the captured current time is in a new day but your time-of-day is shortly before midnight yesterday. If so subtract a day from now. Use whatever boundary time-of-day values make sense in your situation.
if (
lt.isAfter( LocalTime.of( 23 , 55 ) )
&&
odt.toLocalTime().isBefore( LocalTime.of( 0 , 5 ) )
) {
now = now.minusDays( 1 ) ;
}
Adjust from UTC to your desired time zone.
ZoneId z = ZoneId( "Africa/Tunis" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
For Android <26, see the ThreeTenABP 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.
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.
This question already has answers here:
How do I say 5 seconds from now in Java?
(11 answers)
Closed 4 years ago.
How to add 30 seconds to the datetime in the format yyyyMMddHHmmss in java
SO far I have done this
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Date d;
d = df.parse(requestDate);
System.out.println(" date d "+d);
Long time = d.getTime();
time +=30;
Date d2 = new Date(time);
System.out.println(" date d2 "+d2);
And the output I am getting is not correct and both are same time . The output I am getting is
date d Wed Apr 30 19:32:47 IST 2014
date d2 Wed Apr 30 19:32:47 IST 2014
tl;dr
LocalDateTime.parse(
"20180123123456" ,
DateTimeFormatter.ofPattern( “uuuuMMddHHmmss” )
).plusSeconds( 5 )
java.time
Use modern java.time classes rather than terrible old legacy classes.
Parse as a LocalDateTime as your input apparently lacks any indicator of offset or time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( “uuuuMMddHHmmss” ) ;
LocalDateTime ldt = LocalDateTime.parse( “20180123123456” , f ) ;
Duration d = Duration.ofSeconds( 30 ) ; // Represent a span of time unattached to the timeline.
LocalDateTime later = ldt.plus( d ) ;
String output = later.format( f ) ; // Generate a String representing the value of this object.
Tip: Use ISO 8601 standard formats instead.
Search Stack Overflow for more info. This has been covered many times already.
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor 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, 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.
You have the correct idea, but made a small mistake. getTime gives the time in milliseconds, not seconds. So you need to add 30000.
You need add 30000 millisecond(30 sec)where 1000 Millisecond means 1 Second
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Date d;
d = df.parse(requestDate);
System.out.println(" date d "+d);
Long time = d.getTime();
time +=30000;//Here Change
Date d2 = new Date(time);
System.out.println(" date d2 "+d2);
Please read the Date.getTime() doc: Returns the number of milliseconds...
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
Date d;
d = df.parse(requestDate);
System.out.println(" date d "+d);
Long time = d.getTime();
time +=30000; //<---milliseconds
Date d2 = new Date(time);
System.out.println(" date d2 "+d2);
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.
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 )
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();