从Java Date Object查找是否是该月的第一天

时间:2015-05-21 05:09:46

标签: java date

从java.util.Date,最简单/最聪明的方法是找出它是否是一个月的第一天?

3 个答案:

答案 0 :(得分:1)

使用“经典”Java API(Java 8之前版本):

public static boolean isFirstDayOfMonth(final Date date)
{
    final Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    final int dom = cal.get(Calendar.DAY_OF_MONTH);
    return dom == 1;
}

然后你就这样称呼它:

isFirstDayOfMonth(new Date());

答案 1 :(得分:0)

Calendar课程更适合这类事情。

但如果你真的只想用Date来做,那么

        Date d = new Date();
        d = new Date(d.getYear(), d.getMonth(), 0);

        switch (d.getDay()) {
        case 0: System.out.println("Monday");
        break;
        case 1: System.out.println("Tuesday");
        break;
        case 2: System.out.println("Wednessday");
        break;
        case 3: System.out.println("Thusrday");
        break;
        case 4: System.out.println("Friday");
        break;
        case 5: System.out.println("Satureday");
        break;
        case 6: System.out.println("Sunday");
        break;
        }

答案 2 :(得分:0)

Java 8

Date date = new Date();
Instant instant = date.toInstant();
int dom = LocalDateTime.
        ofInstant(instant, ZoneId.systemDefault()).
        getDayOfMonth();
System.out.println(dom);

Joda Time(Pre Java 8)

Date date = new Date();
int dom = LocalDateTime.fromDateFields(date).getDayOfMonth();
System.out.println(dom);