Java时间格式和持续时间

时间:2015-02-19 09:59:46

标签: java time

我需要的输出是:

时间:上午07:00

超时:晚上11:30

持续时间:16小时30分钟

用户需要及时输入和退出,我该怎么办?我搜索了,似乎我需要DateFormat hh:mm:a但我不知道如何使用它。请帮忙。感谢。

3 个答案:

答案 0 :(得分:0)

DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

long timeIn = dateFormat.parse("07:00 AM").getTime();
long timeOut = dateFormat.parse("11:30 PM").getTime();

long duration = (timeOut - timeIn) / 1000 / 60;   // in minutes
long hours = duration / 60;
long minutes = duration % 60;

System.out.println("Time duration: " + hours + " hours and " + minutes + " minutes");

打印:

  

持续时间:16小时30分钟

答案 1 :(得分:0)

你可以尝试这样的事情:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class TimeTracker {

    static Date getTimeIn() {
        //There you must to use your specific Time In getting from user
        //It's just example
        Calendar calendarIn = Calendar.getInstance();

        calendarIn.set(Calendar.HOUR_OF_DAY, 7);
        calendarIn.set(Calendar.MINUTE, 00);
        calendarIn.set(Calendar.SECOND, 0);
        calendarIn.set(Calendar.MILLISECOND, 0 );

        return calendarIn.getTime();
    }

    static Date getTimeOut() {
        //There you must to use your specific Time In getting from user
        //It's just example
        Calendar calendarOut = Calendar.getInstance();

        calendarOut.set(Calendar.HOUR_OF_DAY, 23);
        calendarOut.set(Calendar.MINUTE, 30);
        calendarOut.set(Calendar.SECOND, 0);
        calendarOut.set(Calendar.MILLISECOND, 0);

        return calendarOut.getTime();
    }

    public static void main(String[] args) throws InterruptedException {

        DateFormat formatterTime = new SimpleDateFormat("hh:mm a");
        long timeDuration = getTimeOut().getTime() - getTimeIn().getTime();
        System.out.println("Time in: " + formatterTime.format(getTimeIn()));
        System.out.println("Time out: " + formatterTime.format(getTimeOut()));
        System.out.println("Time duration: " + 
            ((timeDuration / (1000*60*60)) % 24) 
                + " hours and " + 
                    ((timeDuration / (1000*60)) % 60) + " minutes");
     }
}

输出是:

  

时间:上午07:00

     

超时:晚上11:30

     

持续时间:16小时30分钟

答案 2 :(得分:0)

您好,您可以尝试这样的事情

   public String timeDifference(String timeIn,String timeOut){ 
    DateFormat dateFormat=new SimpleDateFormat("hh:mm a");
            String result;
            Date d=dateFormat.parse("08:14 AM");   //First input time in
            Date d1=dateFormat.parse("09:00 PM");   //second input time out

            long min=TimeUnit.MINUTES.convert(d1.getTime()-d.getTime(),TimeUnit.MILLISECONDS);
            System.out.println(min);
            if(min>=60){
                long hrs=min/60;
                result=String.valueOf(min/60)+" hours "+String.valueOf(min%60)+" minutes";

            }
            else
                result=min+" minutes";

            System.out.println(result);
return result;
}