Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java day of the week from string

I have this simple code:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2011-10-29");
calendar.setTime(date);
Log.d("Debug","Day of the week = "+(calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY));

The 29th of October is a Saturday so why do I get false?

like image 365
out_sid3r Avatar asked Oct 29 '11 00:10

out_sid3r


1 Answers

Here is an example of how this could happen...

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try {
        date = format.parse("2011-10-29");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    calendar.setTime(date);
    System.out.println("Day of the week = "
            + (calendar.get(Calendar.DAY_OF_WEEK)));
    System.out.println("Saturday? "
            + (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY));

    try {
        date = format.parse("2011-10-29");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    calendar = Calendar.getInstance(TimeZone.getTimeZone("PST"));
    calendar.setTime(date);
    System.out.println("Day of the week = "
            + (calendar.get(Calendar.DAY_OF_WEEK)));
    System.out.println("Saturday? "
            + (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY));

which outputs

Day of the week = 7
Saturday? true
Day of the week = 6
Saturday? false

so yes, depending on what time zone you are in it will or will not be Saturday.

like image 71
skynet Avatar answered Sep 21 '22 00:09

skynet