Check if the Calendar date is a sunday

前端 未结 3 765
青春惊慌失措
青春惊慌失措 2021-02-14 00:44

I am trying to figure out how to make my program count the number of Sundays in a week.

I have tried the following thing:

if (date.DAY_OF_WEEK == date.SU         


        
3条回答
  •  无人共我
    2021-02-14 01:19

    Note: the Joda-Time project is now in maintenance mode. See this answer if you don't have to work with legacy code.


    If you have to work with date or time a lot, you might want to try using Joda-Time.

    Your code would look something like this:

    LocalDate startDate = new LocalDate(2012, 12, 2);
    int day = startDate.dayOfWeek().get();   // gets the day of the week as integer
    
    if (DateTimeConstants.SUNDAY == day) {
        System.out.println("It's a Sunday!");
    }
    

    You can also get a text string from dayOfWeek():

    String dayText = startDate.dayOfWeek().getAsText();
    

    will return the string "Sunday".

提交回复
热议问题