Reputation: 15
Hi I have a java application where I want to work out if a date string has got the day of the week.
//create the date variable
DateFormat dppomonth = new SimpleDateFormat("MMM dd ''yy");
//find if the string contains "Fri"
private void dppomonthActionPerformed(java.awt.event.ActionEvent evt) {
if(!dppomonth.getDate().toString().contains("Fri")){
JOptionPane.showMessageDialog(this,"Please Select Friday Only...");
dppomonth.setDate(null);
}
}
the getDate()
function has been deprecated how do I find if the string contains "Fri"
if(!dppomonth.getDate().toString().contains("Fri"))
Upvotes: 0
Views: 133
Reputation: 3325
the getDate()
method is deprecated.
you can use the Calendar
class like this:
DateFormat dppomonth = new SimpleDateFormat("MMM dd ''yy");
if (dppomonth.getCalendar().get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY){
}
Upvotes: 0
Reputation: 86203
I think you’re after something like this (the question is not completely clear):
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("MMM d ''uu", Locale.ENGLISH);
String dateString = "Apr 5 '18";
LocalDate date = LocalDate.parse(dateString, dateFormatter);
if (! date.getDayOfWeek().equals(DayOfWeek.FRIDAY)) {
JOptionPane.showMessageDialog(this, "Please Select Friday Only...");
}
As the code stands it does show the message since Apr 5 2018 is a Thursday.
Since you are using Java 8 (and even if you didn’t), I recommend you avoid SimpleDateFormat
. It’s not only long outdated, it is also notoriously troublesome. Instead I am using java.time
, the modern Java date and time API. It is much nicer to work with.
Link: Oracle tutorial: Date Time explaining how to use java.time
.
Upvotes: 2
Reputation: 934
Use Calendar
to make such check like
Date date = ...;
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek != Calendar.FRIDAY) {
System.out.println("Please Select Friday Only...");
}
Upvotes: 3