微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java-如何检查当前时间是否在android中的预设时间范围之间

Hai,我现在有一个问题,我想检查当前时间(10:00 am)是否在预设时间之间
框说(10:00 pm-4:00 am)我该怎么做.
我尝试了一些不总是满足条件的事情

public class Test {

    static int flag;

    public static void main(String[] args) {
        // Todo Auto-generated method stub
        // final Timer timer = new Timer();
        // Timer timer2 = new Timer();

        SimpleDateFormat parser = new SimpleDateFormat("HH.mm");
        Date start = null;
        Date end = null;
        try {
            start = parser.parse("22.00");
        } catch (ParseException e1) {
            // Todo Auto-generated catch block
            e1.printstacktrace();
        }

        try {
            end = parser.parse("8.00");
        } catch (ParseException e1) {
            // Todo Auto-generated catch block
            e1.printstacktrace();
        }

        try {
            Date userDate = parser.parse("23.06");
            if (userDate.after(start) && userDate.before(end)) {
                System.out.println("innnnnnnnnnnn");
            } else {
                System.out.println("outttttttttt");
            }
        } catch (ParseException e) {
            // Invalid date was entered
        }



    }
}

解决方法:

避免约会

通常,众所周知,与Java捆绑在一起的java.util.Date和.Calendar和SimpleDateFormat类非常麻烦,应避免使用.专门针对您的需求,它们结合了日期和时间,而您似乎只需要时间.

请改用一个不错的日期时间库.

>对于Java,这意味着:

> Joda-Time
> java.time package,新于Java 8.

>对于Android,则表示Joda-Time.

当地时间

Joda-Time(和java.time)提供LocalTime类来表示没有任何时区的时间.获取当前时间时,应传递一个DateTimeZone来将计算机/ JVM的日期时间调整为所需的时区,而不是认的时区.

半开

通常在日期时间工作中,比较时间跨度的最佳方法是使用“半开式”方法.半开时,开头是包容性的,结尾是唯一的.注意在此示例代码中使用Joda-Time 2.3进行的比较.

Joda-Time示例

DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
LocalTime Now = LocalTime.Now( timeZone ); // Adjust computer/JVM time zone's current time to desired time zone's current time.
LocalTime start = new LocalTime( "10:00:00" );
LocalTime stop = new LocalTime( "16:00:00" );
boolean isNotBeforeStart = ( ! Now.isBefore( start ) );  // Is Now equal to or after start?
boolean isBeforeEnd = Now.isBefore( stop ); // Is Now any time up to, but not including, stop?
boolean isWithinRange = ( isNotBeforeStart && isBeforeEnd );

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐