如何在java中比较时间字符串和当前时间?

如何在java中比较时间字符串和当前时间?,java,datetime,comparison,Java,Datetime,Comparison,我有一个类似“15:30”的时间字符串,我想将该字符串与当前时间进行比较。 请给我一些简单的建议。 以及如何以小时-分钟格式获取当前时间(“HH:mm”)下面将获取时间。你可以用它来比较 String currentTime=new SimpleDateFormat("HH:mm").format(new Date()); 只需按正常方式比较字符串,如下所示: String currentTime = new SimpleDateFormat("HH:mm").format(new Date(

我有一个类似“15:30”的时间字符串,我想将该字符串与当前时间进行比较。 请给我一些简单的建议。
以及如何以小时-分钟格式获取当前时间(“HH:mm”)

下面将获取时间。你可以用它来比较

String currentTime=new SimpleDateFormat("HH:mm").format(new Date());

只需按正常方式比较字符串,如下所示:

String currentTime = new SimpleDateFormat("HH:mm").format(new Date());
String timeToCompare = "15:30";
boolean x = currentTime.equals(timeToCompare);
如果时间相同,x将为
如果时间不同,x将为

试试这个

public static String compareTime(String d) {
        if (null == d)
            return "";

        try {

            SimpleDateFormat sdf= new SimpleDateFormat("HH:mm");
            d = sdf.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();

        }

        return d;

    }
然后可以与字符串进行比较

tl;博士 细节 您应该换一种方式思考:如何将该字符串转换为时间值。你不会把数字变成字符串来尝试数学。日期时间值也是如此

避免使用旧的捆绑类java.util.Date和.Calendar,因为它们在设计和实现上都有缺陷,非常麻烦。他们被新的城市所取代。而java.time的灵感来自于

两者都提供了一个类来捕获一天中没有任何日期到时区的时间:
LocalTime

java.time 特别是使用java中内置的java.time类。获取本地时区中的当前时间。根据输入字符串构造一天中的时间。与
isBefore
isAfter
isEqual
方法进行比较

LocalTime now = LocalTime.now();
LocalTime limit = LocalTime.parse( "15:30" );
Boolean isLate = now.isAfter( limit );
最好指定所需/预期的时区,而不是隐式地依赖JVM的当前默认时区

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
LocalTime now = LocalTime.now( z );  // Explicitly specify the desired/expected time zone.
LocalTime limit = LocalTime.parse( "15:30" );
Boolean isLate = now.isAfter( limit );
乔达时间 本例中使用Joda时间库的代码恰好与上面看到的java.Time代码几乎相同

请注意,项目现在正在进行中,团队建议迁移到类


关于java.time 该框架内置于Java8及更高版本中。这些类取代了麻烦的旧日期时间类,例如,&

该项目现已启动,建议迁移到类

要了解更多信息,请参阅。并搜索堆栈溢出以获得许多示例和解释。规格是

从哪里获得java.time类

  • ,及以后
    • 内置的
    • 标准JavaAPI的一部分,带有捆绑实现
    • Java9添加了一些次要功能和修复
    • 大部分java.time功能都在中向后移植到Java6和Java7
    • 该项目专门为Android采用了ThreeTen Backport(如上所述)

该项目使用其他类扩展了java.time。这个项目是java.time将来可能添加的一个试验场。您可以在这里找到一些有用的类,如、、和。

我有一个类似的情况,我需要将“15:30”这样的时间字符串与当前时间进行比较。 我使用的是Java7,所以我不能使用Basil Bourque的解决方案。 所以我实现了一个方法,它使用一个字符串,比如“15:30”和 检查当前时间,如果当前时间在输入时间之后,则返回true

public static boolean checkSlaMissedOrNot(String sla) throws ParseException {
        boolean slaMissedOrnot = false;
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(sla.substring(0, 2)));
        cal.set(Calendar.MINUTE, Integer.parseInt(sla.substring(3)));
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        if (Calendar.getInstance().after(cal)) {
            System.out.println("it's SLA missed");
            slaMissedOrnot = true;
        } else {
            System.out.println("it's fine & not SLA missed");
        }
        return slaMissedOrnot;
    }
Calendar还有其他完整的使用方法,如
after(objectwhen)

返回此日历是否表示指定对象表示的时间之后的时间。 您还可以使用此方法将时间字符串与当前时间进行比较


下面是我要比较当前时间前后的示例:

MainActivity.java

Button search = (Button) findViewById(R.id.searchBus);
        SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");

        String limit = "23:00";
        Date limitBus=null;
        try {
            limitBus = sdfDate.parse(limit);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String start = "07:15";
        Date startBus=null;
        try {
            startBus = sdfDate.parse(start);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String user_time = getCurrentTimeStamp();
        Date now = null;
        try {
            now = sdfDate.parse(user_time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (now.after(limitBus)||now.before(startBus)){
            Toast.makeText(this, "Bus Operation Hours : 7:15AM - 11.00PM", Toast.LENGTH_LONG).show();
            search.setEnabled(false);
        }

        else
        {
            search.setEnabled(true);
        }



//get current time method
 public static String getCurrentTimeStamp() {
        SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");//dd/MM/yyyy
        Date now = new Date();
        String strDate = sdfDate.format(now);
        return strDate;
    }

所以我的解决方案有点不同,它首先用当前时间创建一个时钟,然后测试小时,而不是用户定义的int

    public void TextClockWindow() {

    this.pack();

    javax.swing.Timer t = new javax.swing.Timer(1000, (ActionEvent e) -> {
        Calendar calendar = new GregorianCalendar();
        String am_pm;
        calendar.setTimeZone(TimeZone.getDefault());

        Calendar now = Calendar.getInstance();
        int h = now.get(Calendar.HOUR_OF_DAY);
        int m = now.get(Calendar.MINUTE);
        int s = now.get(Calendar.SECOND);

        if (calendar.get(Calendar.AM_PM) == 0) {
            am_pm = "AM";

        } else {
            am_pm = "PM";

        }   // Code to Determine whether the time is AM or PM

        Clock.setText("" + h + ":" + m + " " + am_pm);

        if(h < 5) { //int here which tests agaisnt the hour evwery second
        System.out.println("Success");
        } else {
        System.out.println("Failure"); 
        }
    });
    t.start();
}
public void TextClockWindow(){
这个包();
javax.swing.Timer t=newjavax.swing.Timer(1000,(ActionEvent e)->{
日历=新的公历日历();
上午(下午)时;;
calendar.setTimeZone(TimeZone.getDefault());
Calendar now=Calendar.getInstance();
int h=now.get(日历小时);
int m=now.get(Calendar.MINUTE);
int s=now.get(Calendar.SECOND);
if(calendar.get(calendar.AM\u PM)==0){
am_pm=“am”;
}否则{
am_pm=“pm”;
}//用于确定时间是AM还是PM的代码
Clock.setText(“+h+”:“+m+”+am\U pm);
如果(h<5){//int,这里哪一个不是小时每秒
System.out.println(“成功”);
}否则{
系统输出打印项次(“失败”);
}
});
t、 start();
}
此代码将检查用户输入的时间与当前系统时间,并将返回长值中的时间差

public long getTimeDifferenceInMillis (String dateTime) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        long currentTime = new Date().getTime();
        long endTime = 0;

        try {
            //Parsing the user Inputed time ("yyyy-MM-dd HH:mm:ss")
            endTime = dateFormat.parse(dateTime).getTime(); 
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }

        if (endTime > currentTime)
            return endTime - currentTime;
        else
            return 0;
    }

用户应以格式“yyyy-MM-dd HH:MM:ss”传递时间。

参考SimpleDataFormat是否要“现在”的范围?例如在“12:34.999”,12:34是一个匹配,但1毫秒后它不是-这是你想要的吗?我只想比较当前时间是否大于时间字符串。这是我要比较的时间字符串。String time1End=Integer.toString(calendar.get(calendar.HOUR\u OF_DAY))+“:15”;我把它转换成下面的格式。java.util.Date endTime1=新的SimpleDataFormat(“HH:mm”).parse(time1End);现在将sstemdate转换为上述时间格式。java.util.Date systemdate=new java.util.Date();SimpleDataFormat解析器=新的SimpleDataFormat(“HH:mm”);字符串systemTime=parser.format(systemdate);java.util.Date currentTime=新的SimpleDataFormat(“HH:mm”).parse(systemTime);然后我们可以这样比较。如果(currentTime.after(endTime1))感谢您的回复,我使用的是Java6,您能为java提供相同的解决方案吗6@mayanksharma适用于Java5、6、7和8。只需添加到项目中即可。@mayanksharma更新:Joda Time项目现在处于维护模式。团队建议迁移到java.time类。对于Java6和Java7,您将在ThreeTen Backport项目中发现许多Java.time功能的后端口。对于Android来说,ThreeTenABP。请不要教年轻人使用早已过时且臭名昭著的麻烦软件
public long getTimeDifferenceInMillis (String dateTime) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        long currentTime = new Date().getTime();
        long endTime = 0;

        try {
            //Parsing the user Inputed time ("yyyy-MM-dd HH:mm:ss")
            endTime = dateFormat.parse(dateTime).getTime(); 
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }

        if (endTime > currentTime)
            return endTime - currentTime;
        else
            return 0;
    }