Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to get day of a week as a string, But giving wrong day

Tags:

java

date

I tried to get the day as a string by using the following code. But it returns wrong string. Can I fix it with this code.

private String getDayOfWeek(int value){
    String day = "";
    switch(value){
    case 1:
        day="Sunday";
        break;
    case 2:
        day="Monday";
        break;
    case 3:
        day="Tuesday";
        break;
    case 4:
        day="Wednesday";
        break;
    case 5:
        day="Thursday";
        break;
    case 6:
        day="Friday";
        break;
    case 7:
        day="Saturday";
        break;
    }
    return day;

I implements it as

Calendar c = Calendar.getInstance();    
String dayOfWeek = getDayOfWeek(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);
like image 979
JhonF Avatar asked Sep 18 '13 21:09

JhonF


People also ask

How do you find the day of the week in a string?

getInstance(); String dayOfWeek = getDayOfWeek(Calendar. DAY_OF_WEEK); System. out. println(dayOfWeek);

How do you get the day of the week from a date in Java?

To get the day of week for a particular date in Java, use the Calendar. DAY_OF_WEEK constant.


2 Answers

You need to use

String dayOfWeek = getDayOfWeek(c.get(Calendar.DAY_OF_WEEK));

What you were doing before

String dayOfWeek = getDayOfWeek(Calendar.DAY_OF_WEEK);

is calling your method with a random constant (that happens to be 7) the Calendar class is using to represent the DAY_OF_WEEK field in a date.

What you are actually looking for is getting the value of the day of the week in your Calendar instance, which is what Calendar#get(int)

c.get(Calendar.DAY_OF_WEEK)

returns.


On a related note, try to learn and use an actual debugger as stated in the comments.

like image 198
Sotirios Delimanolis Avatar answered Sep 27 '22 21:09

Sotirios Delimanolis


use getdisplayname method from calender object.

Calendar currentDate=new GregorianCalendar();

String dayOfWeek = currentDate.getDisplayName( Calendar.DAY_OF_WEEK ,Calendar.LONG, Locale.getDefault());
like image 39
vijaya kumar Avatar answered Sep 27 '22 20:09

vijaya kumar