Java 比较字符串中的两个时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23283118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:39:29  来源:igfitidea点击:

Comparing two Time in Strings

javastringtimecomparison

提问by user3505931

I am trying to compare to strings:

我正在尝试与字符串进行比较:

Start Time: 10:00 End Time: 12:00

开始时间:10:00 结束时间:12:00

In actuality there is a start time array that contains my values and an end time array. In this case, it would be structured as such:

实际上,有一个包含我的值和结束时间数组的开始时间数组。在这种情况下,它的结构如下:

 StartTimes[0] = "10:00"
 EndTimes[0] = "12:00"

What is the best way (using java) to find out the duration between the times. The start time will always be before the end time. Should I try to separate the string by minute and hour using regex, then parse the hour and parse the minute, compare, then using that info determine the difference, or is their a method to compare times in java? Note these times are in a 24 hour format, so for an ex. 1:00 PM would display as 13:00.

找出时间之间的持续时间的最佳方法是什么(使用java)。开始时间总是在结束时间之前。我应该尝试使用正则表达式按分钟和小时分隔字符串,然后解析小时并解析分钟,比较,然后使用该信息确定差异,还是它们是比较 java 中时间的方法?请注意,这些时间采用 24 小时格式,因此对于前任。1:00 PM 将显示为 13:00。

采纳答案by sps

You can find the duration using

您可以使用找到持续时间

    String startTime = "10:00";
    String endTime = "12:00";
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    Date d1 = sdf.parse(startTime);
    Date d2 = sdf.parse(endTime);
    long elapsed = d2.getTime() - d1.getTime(); 
    System.out.println(elapsed);

回答by Rod_Algonquin

Use split method to split the 2 times and calculate and parse the duration from there:

使用 split 方法拆分 2 次并从那里计算和解析持续时间:

sample from your question:

来自您的问题的示例:

String StartTimes = "10:00";
String EndTimes = "12:00";
String startTimeParse[] = StartTimes.split(":");
String endTimeParse[] = EndTimes.split(":");
int firstHour = Integer.parseInt(startTimeParse[0]);
int firstMinute = Integer.parseInt(startTimeParse[1]);
int secondHour = Integer.parseInt(endTimeParse[0]);
int secondMinute = Integer.parseInt(endTimeParse[1]);
int durattionHour = secondHour - firstHour;
int durattionMinutes = secondMinute - firstMinute;
System.out.println("Duration : " +durattionHour+":"+durattionMinutes );

回答by Xing Fei

there is no such method to compare.

没有这样的方法可以比较。

you can split the time string using ':'. then parse hour and minute into integer. then calculate the duration.

您可以使用 ':' 分割时间字符串。然后将小时和分钟解析为整数。然后计算持续时间。

int parseTimeString(String s) {
    String[] t = s.split(":");
    return Integer.parseInt(t[0]) * 60 + Integer.parseInt(t[1]); // minutes since 00:00
}

int durationInMinute = parseTimeString(EndTimes[0]) - parseTimeString(StartTimes[0]);

回答by Phong Ca

You should create a Date(now) and add Hour, Minute in it. Get long time and calculate duration.

您应该创建一个日期(现在)并在其中添加小时、分钟。获取长时间并计算持续时间。

    Date now = new Date();
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timezone));
    Calendar.setTime(now);
    calendar.add(Calendar.Hour, 12);
    calendar.add(Calendar.MINUTE, 00);
    Date start = calendar.getTime();

    calendar.add(Calendar.Hour, 10);
    calendar.add(Calendar.MINUTE, 00);
    Date end = calendar.getTime();

    try {
        // in milliseconds
        long diff = d2.getTime() - d1.getTime();

        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000) % 24;

        System.out.print(diffHours + " hours, ");
        System.out.print(diffMinutes + " minutes, ");

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

回答by Basil Bourque

java.time In Java 8

Java 8 中的 java.time

I don't have a computer handy to try this, but you might be able to do something like this in the new java.time package in Java 8. Do not confuse the new java.time with the notoriously troublesome old java.util.Date and .Calendar classes bundled with Java.

我没有手头的计算机来尝试这个,但是您可以在 Java 8 的新 java.time 包中执行类似的操作。不要将新的 java.time 与臭名昭著的旧 java.util 混淆。与 Java 捆绑的日期和 .Calendar 类。

LocalTime start = LocalTime.parse( "11:00" );
LocalTime stop = LocalTime.parse( "14:00" );
Duration duration = Duration.between( start, stop );

回答by user3571254

You can use java.text.SimpleDateFormat and java.util.concurrent.TimeUnit to help you parse, compare, format to the desired format.

您可以使用 java.text.SimpleDateFormat 和 java.util.concurrent.TimeUnit 来帮助您解析、比较、格式化为所需的格式。

SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = format.parse(StartTimes[i]);
Date date2 = format.parse(EndTimes[i]);
long millis = date2.getTime() - date1.getTime(); 

String hourminute = String.format("%02d:%02d",   TimeUnit.MILLISECONDS.toHours(millis),
                                                TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)));
                    System.out.println(hourminute);

The complete code could be something like this:

完整的代码可能是这样的:

import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import java.util.Date;

class TimeCompare
{
    public static void main (String[] args) throws java.lang.Exception
    {

        String[] StartTimes = {"10:00", "7:00"};
        String[] EndTimes = {"12:00", "14:56"};
        for (int i=0; i<StartTimes.length; i++){
            if (StartTimes!=null && StartTimes.length>0 && EndTimes!=null &&EndTimes.length>0){
                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                Date date1 = format.parse(StartTimes[i]);
                Date date2 = format.parse(EndTimes[i]);
                long millis = date2.getTime() - date1.getTime(); 

                String hourminute = String.format("%02d:%02d",   TimeUnit.MILLISECONDS.toHours(millis),
                                            TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)));
                System.out.println(hourminute);

            }
        }

    }


}

sources:

来源:

How to calculate time difference in java?

如何计算java中的时差?

How to convert milliseconds to "hh:mm:ss" format?

如何将毫秒转换为“hh:mm:ss”格式?