Java中的一周中的某一天

时间:2011-02-09 05:06:27

标签: java

PHP有一个内置函数,它接收数据并返回星期几(星期一,星期二等)。 Java有类似的功能吗?

4 个答案:

答案 0 :(得分:5)

旧式(很老......)

import java.util.*;

public class GetDay {
    public static void main(String[] args) {
        Calendar calendar = new GregorianCalendar();
        calendar.set(2011, 1, 9); // 1 = Feb  months are zero based remember
        System.out.println(calendar.get(Calendar.DAY_OF_WEEK));  
    }
}

在java-8中,它可以像

一样简单
LocalDate.now().getDayOfWeek //get day of week for current day
LocalDate.of(2016, 01, 01).getDayOfWeek //get day of week for a particular day

此调用返回DayOfWeek枚举值,该值本身具有一些不错的功能。

答案 1 :(得分:4)

Calendar.DAY_OF_WEEK

Calendar c=Calendar.getInstance();
switch (c.get(Calendar.DAY_OF_WEEK))
{
   case Calendar.MONDAY: ...;
   case Calendar.TUESDAY: ...;
}

答案 2 :(得分:4)

java.util.Calendar.getInstance().get(Calendar.DAY_OF_WEEK);

答案 3 :(得分:1)

您可以使用Calendar类:

示例:

Calendar newCal = new GregorianCalendar();
newCal.set(1997, 2, 1, 0, 0, 0);
newCal.setTime(newCal.getTime());    
int day = newCal.get(Calendar.DAY_OF_WEEK);

参考:

http://www.java-tips.org/java-se-tips/java.util/determine-the-day-of-the-week.html