Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding day of a date in Java

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.

like image 678
riyana Avatar asked Apr 27 '11 06:04

riyana


People also ask

How do you find a name of the day in the given date in Java?

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);

How do you find what day of the week a date is in Java?

To get the day of the week, use Calendar. DAY_OF_WEEK.


1 Answers

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.

like image 65
Jon Skeet Avatar answered Nov 15 '22 20:11

Jon Skeet