3

I need to write a method to get day of week (pacific time) for current time. Is the following code correct?

static Calendar s_calendar = Calendar.getInstance(Locale.US);
static {
    s_calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
}

public static int getDayOfWeek() {
    s_calendar.setTimeInMillis(System.currentTimeMillis());
    return s_calendar.get(Calendar.DAY_OF_WEEK);
}

Thanks.

user256239
  • 17,117
  • 24
  • 75
  • 89

2 Answers2

2

Use below:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"),
    Locale.US);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
Taylor Leese
  • 48,798
  • 27
  • 108
  • 140
  • I created a static Calendar object, because I think it may be expensive to create it at every method call. – user256239 Jul 29 '10 at 01:20
  • Depends on your use case whether or not optimizing the Calendar creation matters. Take a look at this: http://stackoverflow.com/questions/368094/system-currenttimemillis-vs-new-date-vs-calendar-getinstance-gettime – Taylor Leese Jul 29 '10 at 01:34
0

System.currentTimeMillis() returns the millis in UTC. Convert it before you call get(Calendar.DAY_OF_WEEK)

Louis Rhys
  • 32,677
  • 53
  • 143
  • 218
  • I made a test. I didn't see any issue without converting it. Java doc specified that "setTimeInMillis(long millis): millis - the new time in UTC milliseconds from the epoch." http://java.sun.com/javase/6/docs/api/java/util/Calendar.html#setTimeInMillis(long) – user256239 Jul 29 '10 at 17:15