java - 如何在 Android 中比较 AM/PM 时间

标签 java android time calendar

我有一个场景

start-time = 4:15 PM
end-time = 2:00 AM 

如果我的当前时间(比如说晚上 9:15,格式与开始或结束时间相同)在 start-timeend- 之间time 然后转到 screen 1 否则转到 screen 2

我的问题是如何比较大于或等于“开始时间”且小于或等于“结束时间”的 current-time。我尝试将给定时间值转换为 毫秒 并进行比较,但 current-time = 9:15 PM 似乎大于 'end-time = 2: 00 AM',因为 2:00 AM 将在午夜之后到来,这意味着如果“9:15 PM day = Thursday then 2:00 AM will be the Friday”。我搜索了很多但无法弄清楚。我们将不胜感激任何类型的帮助。

已编辑:

当前时间、开始时间和结束时间的所有值都取为 String

编辑 2

代码斯皮内特:

long currentTime = getMillis("9:15 PM");

long startTime = getMillis("4:15 PM");

long endTime = getMillis("2:00 AM");//this will be the next day's time confusing part for me

if(currentTime >= startTime && currentTime <= endTime)
{
   //goto screen 1
}
else
{
  // goto screen 2
}


private long getMillis(String givenTime)
{
   SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
try {
    Date mDate = sdf.parse(givenTime);
    long timeInMilliseconds = mDate.getTime();
    System.out.println("Date in milli :: " + timeInMilliseconds);
    return timeInMilliseconds;
} catch (ParseException e) {
            e.printStackTrace();
}
return 0;
}

最佳答案

第 1 步: 您只需在结束时间早于开始时间时向其添加一天

第 2 步: 应用您的条件检查当前时间是否在开始时间和结束时间之间

    try {
        Date mToday = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
        String curTime = sdf.format(mToday);
        Date start = sdf.parse("4:15 PM");
        Date end = sdf.parse("2:00 AM");
        Date userDate = sdf.parse(curTime);

        if(end.before(start))
        {
            Calendar mCal = Calendar.getInstance();
            mCal.setTime(end);
            mCal.add(Calendar.DAY_OF_YEAR, 1);
            end.setTime(mCal.getTimeInMillis());
        }

        Log.d("curTime", userDate.toString());
        Log.d("start", start.toString());
        Log.d("end", end.toString());


        if (userDate.after(start) && userDate.before(end)) {
            Log.d("result", "falls between start and end , go to screen 1 ");
        }
        else{
            Log.d("result", "does not fall between start and end , go to screen 2 ");
        }
    } catch (ParseException e) {
        // Invalid date was entered
    }

关于java - 如何在 Android 中比较 AM/PM 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25890072/

相关文章:

java - Spring 应用上下文 : webapp folder variable?

android - 如何将一项服务绑定(bind)到多个应用程序

mysql - 如何查询 sql 以获取每个用户的最新记录日期和时间

javascript - 在时间格式 hh :mm:ss 的数组中查找时间总和

android - 不同设备上的印地语字符 View 不同

time - Big-O:n ^ 2 =Ω(n log n)?

java - 在 TAI 中以编程方式验证用户身份

java - 如何从对象的变量之一内部获取对象的实例

java - 大型哑数据对象的最佳实践?

android - 如何为按钮的按下状态设置不同的颜色?