Java Day Date Search

I want to know the day of the date in Java, for example, 27-04-2011 .

I tried using this, but it does not work:

 Calendar cal = Calendar.getInstance(); int val = cal.get(Calendar.DAY_OF_WEEK); 

It gives an integer value, not the string output that I want. I am not getting the correct value that I want. For example, this gives me a value of 4 for the date 28-02-2011 , where it should be 2, because Sunday is the day of the first week.

+7
source share
7 answers

Yes, you asked him for a week - and February 28 was Monday, the second day . Please note that in the code you provided, you do not actually set the date anywhere - it just uses the current date, which is Wednesday, so you get 4. If you could show how you are trying to set the calendar to a different date (for example February 28), we can decide why this does not work for you.

If you want to format it as text, you can use SimpleDateFormat and the qualifier "E". For example (untested):

 SimpleDateFormat formatter = new SimpleDateFormat("EEE"); String text = formatter.format(cal.getTime()); 

Personally, I would avoid using Calendar at all, though - use Joda Time , which is a much more advanced API with date and time.

+9
source
 Calendar cal=Calendar.getInstance(); System.out.println(new SimpleDateFormat("EEE").format(cal.getTime())); 

Exit

 Wed 

see also

+3
source
  String dayNames[] = new DateFormatSymbols().getWeekdays(); Calendar date1 = Calendar.getInstance(); System.out.println("Today is a " + dayNames[date1.get(Calendar.DAY_OF_WEEK)]); 
+3
source

See the JavaDoc field of the DAY_OF_WEEK field. It points to 7 SUNDAY..SATURDAY constants that show how to decode the return value of int cal.get (Calendary.DAY_OF_WEEK). You are sure that

 Calendar cal = Calendar.getInstance(); cal.set(2011, 02, 28); cal.get(Calendar.DAY_OF_WEEK); 

returns the wrong value for you?

+1
source

Try the following:

  Calendar cal=Calendar.getInstance(); int val = cal.get(Calendar.DAY_OF_WEEK); System.out.println(new DateFormatSymbols().getWeekdays()[val]); 

or

  Calendar cal=Calendar.getInstance(); String dayName = new DateFormatSymbols().getWeekdays()[cal .get(Calendar.DAY_OF_WEEK)]; System.out.println(dayName); 
+1
source
 Calendar cal=Calendar.getInstance(); cal.set(2011, 2, 28); int val = cal.get(Calendar.DAY_OF_WEEK); System.out.println(val); 
+1
source

Take a look at SimpleDateFormat and propably Locale .

0
source

All Articles