I want to find out the day of the date in Java for a date like 27-04-2011
.
I tried to use this, but it doesn't work:
Calendar cal = Calendar.getInstance();
int val = cal.get(Calendar.DAY_OF_WEEK);
It gives the integer value, not the String output I want. I am not getting the correct value I want. For example it is giving me value 4
for the date 28-02-2011
where it should be 2 because Sunday is the first week day.
Core Java bootcamp program with Hands on practice // displaying full-day name f = new SimpleDateFormat("EEEE"); String str = f. format(new Date()); System. out. println("Full Day Name = "+str);
To get the day of the week, use Calendar. DAY_OF_WEEK.
Yes, you've asked it for the day of the week - and February 28th was a Monday, day 2. Note that in the code you've given, you're not actually setting the date anywhere - it's just using the current date, which is a Wednesday, which is why you're getting 4. If you could show how you're trying to set the calendar to a different date (e.g. 28th of February) we can work out why that's not working for you.
If you want it formatted as text, you can use SimpleDateFormat
and the "E" specifier. For example (untested):
SimpleDateFormat formatter = new SimpleDateFormat("EEE");
String text = formatter.format(cal.getTime());
Personally I would avoid using Calendar
altogether though - use Joda Time, which is a far superior date and time API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With