check if date() is monday? java

后端 未结 4 496
别跟我提以往
别跟我提以往 2021-02-08 03:34

Is there a way to check if a java Date object is Monday? I see you can with a Calendar object, but date? I\'m also using US-eastern date and time if th

相关标签:
4条回答
  • 2021-02-08 04:02

    The question doesn't make sense without two extra pieces of information: a time zone and a calendar system.

    A Date object just represents an instant in time. It happens to be Wednesday in the Gregorian calendar in my time zone - but for some folks to the east of me, it's already Thursday. In other calendar systems, there may not even be such a concept of "Monday" etc.

    The calendar system part is probably not a problem, but you will need to work out which time zone you're interested in.

    You can then create a Calendar object and set both the time zone and the instant represented - or, better, you could use Joda Time which is a much better date/time API. You'll still need to think about the same questions, but your code will be clearer.

    0 讨论(0)
  • 2021-02-08 04:04

    You can use Calendar object.

    Set your date to calendar object using setTime(date)

    Example:

    calObj.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY
    

    EDIT: As Jon Skeet suggested, you need to set TimeZone to Calendar object to make sure it works perfect for the timezone.

    0 讨论(0)
  • 2021-02-08 04:09

    Something like this will work:

    Calendar cal = Calendar.getInstance();
    cal.setTime(theDate);
    boolean monday = cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY;
    
    0 讨论(0)
  • 2021-02-08 04:11

    You should use Calendar object for these checks. Date has weak timezones support. In one timezone this Date can be Monday, and in another timezone it is still Sunday.

    0 讨论(0)
提交回复
热议问题