开发者

java - I have a Date(). How do I know if it is after HH:MM or not? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

How do I compare a raw time in Java to n开发者_如何转开发ow?

How do I compare a raw time in Java?

It doesnt matter which day.

I have to know if currently it is after 10AM or before.


You can use:

Date yourDate = new Date();

GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(yourDate);
boolean before10AM = calendar.get(Calendar.HOUR_OF_DAY) < 10;

Check out the documentation for Calendar to find out more of the stuff you can do with it (such as, for example, you can find out if your date is a friday or not).

In previous versions of the JDK, you could use Date.getHours(), but that is now deprecated in favor of the Calendar class.


Here you go:

    Date date = new Date();
    int hours = date.getHours();

    if ( hours < 10) {
        System.out.println("before 10 am");
    } else {
        System.out.println("after 10 am");
    }

    // if deprecated methods are an issue then
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);

    int calHours = cal.get(Calendar.HOUR_OF_DAY);
    if ( calHours < 10) {
        System.out.println("before 10 am");
    } else {
        System.out.println("after 10 am");
    }

The whole thing can be done a lot more cleanly using the joda-time library.


Calendar calendar = new GregorianCalendar();
    calendar.setTime(yourDate);

    Calendar calendar1 = new GregorianCalendar();
    calendar1.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
    calendar1.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
    calendar1.set(Calendar.DATE, calendar.get(Calendar.DATE));
    calendar1.set(Calendar.HOUR_OF_DAY, YOUR_HOUR);
    calendar1.set(Calendar.MINUTE, YOUR_MINUTE);
    calendar1.set(Calendar.SECOND, 0);
    calendar1.set(Calendar.MILLISECOND, 0);

    Date date = calendar1.getTime();

    if (yourDate.after(date)) {
      System.out.println("After");
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜