Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get day of the week from GregorianCalendar

Tags:

I have a date and I need to know the day of the week, so I used a GregorianCalendar object but I get back some dates that are incorrect.

GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);

What am I doing wrong?

Thanks!

EDIT SOLUTION:

mont--;
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);

    if(i == 2){
        dayOfTheWeek = "Mon";           
    } else if (i==3){
        dayOfTheWeek = "Tue";
    } else if (i==4){
        dayOfTheWeek = "Wed";
    } else if (i==5){
        dayOfTheWeek = "Thu";
    } else if (i==6){
        dayOfTheWeek = "Fri";
    } else if (i==7){
        dayOfTheWeek = "Sat";
    } else if (i==1){
        dayOfTheWeek = "Sun";
    }
like image 399
MataMix Avatar asked Sep 23 '11 03:09

MataMix


People also ask

What is Oracle Gregorian calendar?

GregorianCalendar is a hybrid calendar that supports both the Julian and Gregorian calendar systems with the support of a single discontinuity, which corresponds by default to the Gregorian date when the Gregorian calendar was instituted (October 15, 1582 in some countries, later in others).

How do you use the Gregorian calendar?

The days of the year in the Gregorian calendar are divided into 7-day weeks, and the weeks are numbered 1 to 52 or 53. The international standard is to start the week on Monday. However, several countries, including the US and Canada, count Sunday as the first day of the week.

What is the return type for the getGregorianChange () method?

getGregorianChange() is an inbuilt method in Java which returns the Gregorian Calendar change date which is the change from Julian Calendar dates to Gregorian Calendar dates.


2 Answers

TimeZone timezone = TimeZone.getDefault();
Calendar calendar = new GregorianCalendar(timezone);
calendar.set(year, month, day, hour, minute, second);

String monthName=calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());//Locale.US);
String dayName=calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault());//Locale.US);
like image 70
Benn Sandoval Avatar answered Sep 21 '22 17:09

Benn Sandoval


Joda-Time

I use Joda-Time library for all date/time related operations. Joda takes into account you locale and gets results accordingly:

import org.joda.time.DateTime;
DateTime date = new DateTime(year, month, day, 0, 0, 0);

or

DateTime date = DateTime().now();

Day of week (int):

date.getDayOfWeek();

Day of week (short String) using toString() and DateTimeFormat options:

date.toString("EE");
like image 23
jki Avatar answered Sep 23 '22 17:09

jki