How the get the current day name using particular date in android?-ThrowExceptions

Exception or error:

I have date string 18-2-2012 , from this how to get the current day name i.e., today is “saturday” like this. for tomorrow’s date 19-2-2012 and the day name is “sunday“.

How to solve:

Use java date formats.

SimpleDateFormat inFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inFormat.parse(input);
SimpleDateFormat outFormat = new SimpleDateFormat("EEEE");
String goal = outFormat.format(date); 

###

You can use Calendar

            Calendar calendar = Calendar.getInstance();

            calendar.setTime(date_your_want_to_know);

            String[] days = new String[] { "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" }

            String day = days[calendar.get(Calendar.DAY_OF_WEEK)];

###

Just use a single line of code:

android.text.format.DateFormat.format("EEEE", date);

###

int dayOfWeek=bday.get(Calendar.DAY_OF_WEEK);  // Returns 3, for Tuesday!

for more detail go here….
http://mobile.tutsplus.com/tutorials/android/java_android_date-and-time/

###

First convert the date string to a Date using SimpleDateFormat.

Then make a Calendar instance from that date.

Finally, retrieve the day of week from the Calendar using the get(Calendar.DAY_OF_WEEK). This will give you an integer between 1 to 7 representing the day of the week. You can simple map this to an array of Strings to get the days.

###

On @vivek’s answer add “-1” at calendar.get(Calendar.DAY_OF_WEEK), since it returns numbers from 1 to 7 but the String array is indexed from 0 to 6.

calendar.setTime(date_your_want_to_know);

String[] days = new String[] { "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" }

String day = days[calendar.get(Calendar.DAY_OF_WEEK)-1];

###

Try this code. Hope it will work.
This is worked for me.

public String daysNameOfWeek(String inputDate){

    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.UK);
    try {

        Date date = df.parse(inputDate.trim());
        SimpleDateFormat outFormat = new SimpleDateFormat("EEEE");
         daysName  = outFormat.format(date);

    } catch (ParseException e) {
        e.printStackTrace();
    }


    return daysName;
}

###

Below method will return the day by passing the date in String format.
null is returned if exception occurs.

private String getDay(String date_in_string_format){        
        DateFormat df = DateFormat.getDateInstance();
        Date date;
        try {
             date = df.parse(date_in_string_format);
        } catch (Exception e) {
            Log.e("Error:","Exception " + e);
            return null;
        }
        return new SimpleDateFormat("EEEE").format(date);
    }

Hope it helps.

Leave a Reply

Your email address will not be published. Required fields are marked *