简体   繁体   中英

Getting the day of the week from user input

Date date= (new GregorianCalendar(year, month, day)).getTime();
SimpleDateFormat f = new SimpleDateFormat("EEEE");
String dow=f.format(date);

System.out.print("This date is a "+dow);

I have the user input a month(1-12) a day(1-31) and a year(1600-2400) It works fine only it displays the wrong day. For example it says that Jan 1st 2014 is a Saturday but it was a Wednesday. It is probably because I didn't factor in leap years but I don't have a clue to go about doing that. Neither do I know how to tell it how many days in each month. An array? Hopefully minimal lines as well.

Thanks so much!!! This has been bugging me for an hour +. And something so simple, I should have figured. I must be tired.

Thanks!!!!!!!

Month is Zero based. Try,

Date date= (new GregorianCalendar(year, month-1, day)).getTime();
    SimpleDateFormat f = new SimpleDateFormat("EEEE");
    String dow=f.format(date);

The answer by Shashank Kadne is correct.

Joda-Time

FYI, this work is simpler and cleaner using the Joda-Time 2.3 library.

Joda-Time uses sensible one-based counting for things such as:

  • Month-of-Year
    January = 1, February = 2, and so on.
  • Day-of-Week
    Monday = 1, Sunday = 7. (Standard ISO 8601 week)

Joda-Time DateTime objects know their own time zone, unlike java.util.Date objects.

Joda-Time leverages a specified Locale object to render localized strings.

Example Code

// Specify a time zone rather than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );

int year = 2014;
int month = 1; // Sensible one-based counting. January = 1, February = 2, …
int dayOfMonth = 2;

DateTime dateTime = new DateTime( year, month, dayOfMonth, 0, 0, 0, timeZone );

// Day-of-week info.
int dayOfWeekNumber = dateTime.getDayOfWeek(); // Standard week (ISO 8601). Monday = 1, Sunday = 7.
DateTime.Property dayOfWeekProperty = dateTime.dayOfWeek();
String dayOfWeekName_Short = dayOfWeekProperty.getAsShortText( Locale.FRANCE );
String dayOfWeekName_Long = dayOfWeekProperty.getAsText( Locale.FRANCE );

Dump to console…

System.out.println( "dateTime: " + dateTime );
System.out.println( "dayOfWeekNumber: " + dayOfWeekNumber );
System.out.println( "dayOfWeekName_Short: " + dayOfWeekName_Short );
System.out.println( "dayOfWeekName_Long: " + dayOfWeekName_Long );

When run…

dateTime: 2014-01-02T00:00:00.000+01:00
dayOfWeekNumber: 4
dayOfWeekName_Short: jeu.
dayOfWeekName_Long: jeudi

Without Time & Time Zone

If you truly want only date without any time or time zone, then write similar code but with the LocalDate class.

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