java 检查 date() 是否是星期一?爪哇
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12080391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check if date() is monday? java
提问by Jake Long
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 that changes indexing of monday
有没有办法检查一个javaDate
对象是否是星期一?我看到你可以用一个Calendar
对象,但约会?如果星期一的索引发生变化,我也会使用美国东部的日期和时间
回答by Dan D.
Something like this will work:
像这样的事情会起作用:
Calendar cal = Calendar.getInstance();
cal.setTime(theDate);
boolean monday = cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY;
回答by kosa
You can use Calendar
object.
您可以使用Calendar
对象。
Set your date to calendar object using setTime(date)
使用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.
编辑:正如 Jon Skeet 所建议的,您需要将 TimeZone 设置为 Calendar 对象,以确保它适合时区。
回答by Jon Skeet
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 mytime 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.
一个Date
对象只是代表一个瞬间。这恰好是我所在时区公历中的星期三——但对于我东部的一些人来说,已经是星期四了。在其他日历系统中,甚至可能没有“星期一”等这样的概念。
The calendar system part is probably not a problem, but you willneed 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 Timewhich is a muchbetter date/time API. You'll still need to think about the same questions, but your code will be clearer.
然后,您可以创建一个Calendar
对象,并同时设置时区和即时代表-或者更好,你可以使用约达时间是一个多更好的日期/时间API。您仍然需要考虑相同的问题,但您的代码会更清晰。
回答by March
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.
您应该使用 Calendar 对象进行这些检查。日期的时区支持较弱。在一个时区,这个日期可以是星期一,而在另一个时区它仍然是星期日。