简体   繁体   中英

Android : Set the date and get day of week

I have problems Set the date and get day of week

set 2011/1/17 ==> get Monday

   Date d = new Date();

d.setDate(17);
d.setMonth(1);
d.setYear(2011);

    SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
    String dayOfWeek = sdf.format(d);

/* - - - - - - - - - - OR - - - - - - - - - - - - - - - */

    Calendar c = Calendar.getInstance();

c.set(2011, 1, 17);

    int day = c.get(Calendar.DAY_OF_WEEK);
    String weekDay="";

    switch (day) {
                case Calendar.SUNDAY: weekDay = "Sunday"; break;
                case Calendar.MONDAY: weekDay = "Monday"; break;
                case Calendar.TUESDAY: weekDay = "Tuesday"; break;
                case Calendar.WEDNESDAY: weekDay = "Wednesday"; break;
                case Calendar.THURSDAY: weekDay = "Thursday"; break;
                case Calendar.FRIDAY: weekDay = "Friday"; break;
                case Calendar.SATURDAY: weekDay = "Saturday"; break;
              }

Remember January should be 0 in java Calendar. To set 2011/01/17 it should be 2011/00/17.

c.set(2011, 0, 17);
//or c.set(2011, Calendar.JANUARY, 17);

int day = c.get(Calendar.DAY_OF_WEEK);
String weekDay="";

switch (day) {
            case Calendar.SUNDAY: weekDay = "Sunday"; break;
            case Calendar.MONDAY: weekDay = "Monday"; break;
            case Calendar.TUESDAY: weekDay = "Tuesday"; break;
            case Calendar.WEDNESDAY: weekDay = "Wednesday"; break;
            case Calendar.THURSDAY: weekDay = "Thursday"; break;
            case Calendar.FRIDAY: weekDay = "Friday"; break;
            case Calendar.SATURDAY: weekDay = "Saturday"; break;
          }

you can use this

Calendar cal = Calendar.getInstance();
cal.set(2011, 0, 17);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE",Locale.getDefault());
String dayInStrinFormat = sdf.format(cal.getTime());

0 for January .... 11 for December

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM