如何在android中检查开始时间和结束时间?

时间:2014-07-03 08:03:34

标签: android date time

我开发Android应用程序。我的问题我得到字符串开始时间和结束时间。我想开始的时间比当前时间和当前时间少于结束时间。如何在android我的代码下面可能。请帮我!!!

 String sTartTime ="8:0" ;
    String eNdTime = "20:20";
    Calendar c = Calendar.getInstance();
    SimpleDateFormat formatShort = new SimpleDateFormat("H:m", Locale.US);
    String formattedtime = formatShort.format(c.getTime());

 try {

                    String string1 = eNdTime;
                    Date time1 =  new SimpleDateFormat("HH:mm:ss").parse(string1);
                    Calendar calendar1 = Calendar.getInstance();
                    calendar1.setTime(time1);

                    String string2 = sTartTime;
                    Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
                    Calendar calendar2 = Calendar.getInstance();
                    calendar2.setTime(time2);
                    calendar2.add(Calendar.DATE, 1);

                    String someRandomTime = formattedtime;
                    Date d =  new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
                    Calendar calendar3 = Calendar.getInstance();
                    calendar3.setTime(d);
                    calendar3.add(Calendar.DATE, 1);

                    Date x = (Date) calendar3.getTime();
                    if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
                        //checkes whether the current time is between 14:49:00 and 20:11:13.
                         Log.v("log_tag", "Time check today True " );
                    }else{
                        Log.v("log_tag", "Time check today false " );
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

但我无法获得日期对象。我得到错误类型不匹配:无法从java.util.Date转换为java.sql.Date

感谢!!!

1 个答案:

答案 0 :(得分:2)

删除java.sql.Date的导入。我已经测试了你的代码它正在进行小调整。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

class HelloWorldApp {

public static void main(String[] args) {
    System.out.println("Hello World!"); // Display the string.
    String sTartTime ="8:0:0" ;
    String eNdTime = "16:20:00";
    String nowTime = "12:20:00";

    try {

        String string1 = eNdTime;
        Date endDate =  new SimpleDateFormat("HH:mm:ss").parse(string1);

        String string2 = sTartTime;
        Date beforeDate = new SimpleDateFormat("HH:mm:ss").parse(string2);

        String someRandomTime = nowTime;
        Date inBeforeDate =  new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);

        if (inBeforeDate.after(beforeDate) && inBeforeDate.before(endDate)) {
            //checkes whether the current time is between 14:49:00 and 20:11:13.
            System.out.println("log_tag" + "Time check today True " );
        }else{
            System.out.println("log_tag" + "Time check today false " );
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
}