Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

java date/calendar invalid roll? 1

Status
Not open for further replies.

birney29

Programmer
Oct 11, 2001
140
GB
Hi there,

im doing some calculations with dates/calendars. Sometimes the result of these calculations will be invalid, eg, 31st september. Jave automatically "rolls" the date forward to the 31st of october. Howver, i need it to roll back to to the next vaild date, eg 31st of september. is there any way to tell my code to roll back, rather than forward?

Thanks

Kenneth Birney
User Interface Programmer
Scottish Police
 
Hi, take a look at the below code. It parses a date, and then if Java has bumped the date forward, then it recalculates the date.

Code:
		String dd = "32";
		String MM = "03";
		String yy = "04";
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
		java.util.Date master = sdf.parse(dd +"/" +MM +"/" +yy, new ParsePosition(0));
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(master);

		if (gc.get(Calendar.DAY_OF_MONTH) == Integer.parseInt(dd)) {
			// OK, date parsing was fine
		} else {
			// The day of the month was not correct so Java bumpred the date on,
			// but we don't want to do that, so roll it back a day and re-parse
			int tmp = Integer.parseInt(dd);
			tmp--;
			dd = ""+tmp;
			master = sdf.parse(dd +"/" +MM +"/" +yy, new ParsePosition(0));
			gc = new GregorianCalendar();
			gc.setTime(master);
		}

		java.util.Date parsedDate = gc.getTime();

		System.err.println(parsedDate);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top