xnanx
xnanx

Reputation: 1

how to get yesterday instance from jdatechooser

The user needs to select any date (Userdate). I need to set another jdate one day behind this date (needdate). Can you help with this?

Date date1 = (Userdate.getDate(),-1);
needdate.setDate(date1)

Upvotes: -1

Views: 112

Answers (1)

DevilsHnd - 退した
DevilsHnd - 退した

Reputation: 9192

The reason why everyone is telling you to use the new java.time package classes like LocalDate and LocalDateTime etc is because Date is quite old and known to be error prone. But hey...if you're bent on using Date then I suppose you can do it this way:

// Get the date from the JDateChooser
Date date = jDateChooser1.getDateEditor().getDate();

// Subtract one day from the selected JDateChooser date.
Date oneDayFromSelectedDate = new Date(date.getTime() - Duration.ofDays(1).toMillis());

// Define the format you want the Date String;
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

// Dump it into a String variable and...
String myDateString = sf.format(oneDayFromSelectedDate);

//  Display it into the Console Window
System.out.println(myDateString);

The oneDayFromSelectedDate is the Date object containing the JDateChooser selected date less one day. Do consider changing to the java.time package.

Upvotes: 0

Related Questions