Reputation: 47
I have to put a date one week before and then 1 month before. If i try with the days one week before is working but if the day es 5 and it has to change the month is not working, it changes me the year instead. About the month it changes me the year tring addUrl = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
// surround below line with try catch block as below code throws checked
// exception
Date endDate = sdf.parse(request.getParameter(field.getId()));
Calendar cal = DateToCalendar(endDate);
cal.setTime(endDate);
SimpleDateFormat formatToSend = new SimpleDateFormat("yyy-mm-dd");
case "day":
cal.add(Calendar.DATE, -1);
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
break;
case "week":
cal.add(Calendar.DATE, -6); // number of days to add
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
break;
default:
cal.add(Calendar.MONTH, -1); // number of days to add
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
}
How i can do that?
Thanks
Upvotes: 0
Views: 157
Reputation: 339342
Never use the terribly-flawed legacy date-time classes such as Date
, Calendar
, SimpleDateFormat
, etc.
Use only java.time classes. For a date only value, without time-of-day, and without time zone, use LocalDate
.
Specify your starting date.
LocalDate start = LocalDate.parse( "2025-01-23" ) ;
Calculate yesterday.
LocalDate yesterday = start.minusDays( 1 ) ;
Determine the date a week ago.
LocalDate weekPrior = start.minusWeeks( 1 ) ;
Determine a month ago.
LocalDate monthPrior = start.minusMonths( 1 ) ;
Upvotes: 1
Reputation: 383
Im not sure do i fully understand the question however one potential problem is in your date format
m = Minute in hour
M = Month in year <- maybe the one you want?
See here for more examples.
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Upvotes: 0
Reputation: 206896
In your SimpleDateFormat
objects, you should use MM
for months and not mm
, because mm
means minutes, not months.
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat formatToSend = new SimpleDateFormat("yyyy-MM-dd");
See the API documentation of java.text.SimpleDateFormat
.
Upvotes: 2