Comparing two Time in Strings

安稳与你 提交于 2019-12-30 06:33:11

问题


I am trying to compare to strings:

Start Time: 10:00 End Time: 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.


回答1:


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);



回答2:


java.time In Java 8

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.

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



回答3:


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

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 );



回答4:


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]);



回答5:


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();
    }



回答6:


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

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?

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



来源:https://stackoverflow.com/questions/23283118/comparing-two-time-in-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!