比较小时数(字符串到小时和实际小时)

时间:2017-07-01 14:33:02

标签: java android date

我试图将实际的小时和分钟与像这样的“18:00”这样的字符串进行比较。我得到这样的实际小时和分钟:

Calendar now = Calendar.getInstance();

int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);

date = parseDate(hour + ":" + minute);

我有一个像这样的字符串“18:00”(TAG_HORA),我试图比较这样的2个日期:

dateCompareOne = parseDate(c.getString(TAG_HORA));
if ((dateCompareOne.after(date))){//...

我没有得到结果,有人可以帮助我吗?感谢

3 个答案:

答案 0 :(得分:2)

您可以使用TAG_HORAString.split()Integer.valueOf()中提取小时和分钟。然后,很容易比较时间。

Calendar now = new GregorianCalendar();
int nowHour = now.get(Calendar.HOUR);
int nowMin = now.get(Calendar.MINUTE);


String hora = "18:00";
String[] parts = hora.split(":");

int horaHour = Integer.valueOf(parts[0]);
int horaMinute = Integer.valueOf(parts[1]);

if(60 * nowHour + nowMin > 60 * horaHour + horaMinute) {

}

答案 1 :(得分:1)

如果你不介意你可以做的第二个和几毫秒的流程:

Calendar now = Calendar.getInstance();
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
now.getTimeInMillis();

使用密钥TAGֹ_HORA解析值传递。 然后比较使用<> =唱歌

答案 2 :(得分:1)

我希望这可以提供帮助:

import java.util.Calendar;
import java.lang.Math; // headers MUST be above the first class
import javax.xml.bind.DatatypeConverter;
import static javax.xml.bind.DatatypeConverter.parseDate;

// one class needs to have a main() method
public class test
{
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {

    Calendar now = Calendar.getInstance();
    int hour = now.get(Calendar.HOUR);
    int minute = now.get(Calendar.MINUTE);

    Calendar date1 = Calendar.getInstance();
    date1.set(Calendar.HOUR_OF_DAY, date1.getTime().getHours() );
    date1.set(Calendar.MINUTE, date1.getTime().getMinutes() );
    date1.set(Calendar.SECOND, 0);

    String reference = "18:00";
    String[] parts = reference.split(":");
    Calendar date2 = Calendar.getInstance();
    date2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
    date2.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
    date2.set(Calendar.SECOND, 0);

    if (date1.before(date2)) {
        System.out.println(date1.getTime()+" vs "+date2.getTime());
        System.out.println("Not yet at the limit");
    }

  }
}

编辑:输出为:

Sat Jul 01 16:05:00 GMT+01:00 2017 vs Sat Jul 01 18:00:00 GMT+01:00 2017
Not yet at the limit