java中的时间比较是在字符串中吗? [英] Time comparation in java these are in string?

查看:87
本文介绍了java中的时间比较是在字符串中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个时间用hh:mm:ss格式的字符串。如何比较两个字符串。



我尝试了什么:



I have two timings with hh:mm:ss format in string.How to compare two strings.

What I have tried:





Time comparation in java these are in string?

推荐答案

试试这个并适应:
import java.util.*;
import java.lang.*;
import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;

class Rextester
{  
    public static void main(String args[])
    {
        String startTime = "10:15:20 am";
        String endTime = "12:30:37 pm";

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
        try {
            
            Date d1 = sdf.parse(startTime);
            
            Date d2 = sdf.parse(endTime);
  
            long elapsed = d2.getTime() - d1.getTime(); 
            
            int hours = (int) Math.floor(elapsed / 3600000);
            
            int minutes = (int) Math.floor((elapsed - hours * 3600000) / 60000);
            
            int seconds = (int) Math.floor((elapsed - hours * 3600000 - minutes * 60000) / 1000);
            
            System.out.format("From %s to %s%n", startTime, endTime);
                                    
            System.out.format("Time elapsed %d milliseconds%n", elapsed);
            
            System.out.format("%d hours %d minutes %d seconds%n", hours, minutes, seconds);


         } catch (ParseException e) {
              e.printStackTrace();
         }
    }
}

或查看演示 [ ^ ]

参考:SimpleDateFormat:日期格式 « 数据类型 «  Java教程 [ ^ ]

or view Demo[^]
reference: SimpleDateFormat : Date Format « Data Type « Java Tutorial[^]


包含所有细节没有给我们任何答案是对的。

With all the details you didn't gave us, about any answer is right.
引用:

hh:mm:ss



这个时间格式是Europa中使用的24小时时间格式,在美国也称为军事时间格式。

如果目标是比较< =>,直接字符串比较就可以了。

如果目标是获得时差,则需要转换为时间数据类型。


This time format is the 24 hours time format as used in Europa, also known as military time format in USA.
If the goal is to compare like < = >, direct string comparison do the trick.
If the goal is to get the time difference, a conversion to time datatype is necessary.


这篇关于java中的时间比较是在字符串中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆