在Java中减去两次

时间:2015-01-09 21:12:12

标签: java time

在我提出一个关于减去时间的问题之前,我认为我已经拥有了它。但是当我调试时,出现了几个错误。基本上我要问的是创建一个打卡时钟,但我不能使用Java Calendar API。

用户将输入开始时间和他们打孔的时间,并计算时间之间的差异。

我的工作效果不好,我不知道为什么。例如,如果上午4:00是开始,上午12:00是结束,则返回8小时00分钟。那是不对的。我以为我为可能性创建了一个if语句。

这是我的代码:

     public static void elapsedTime()
    {
        Scanner reader = new Scanner (System.in);

        System.out.print("Enter the beginning hour: ");
        int startingHour = reader.nextInt();

        System.out.print("Enter the beginning minute(s): ");
        int startingMin = reader.nextInt();


        System.out.print("Enter AM/PM: ");
        reader.nextLine();
        String startingTOD = reader.nextLine();


        System.out.print("Enter the ending hour: ");
        int endingHour = reader.nextInt();

        System.out.print("Enter the ending minute(s): ");
        int endingMin = reader.nextInt();

        System.out.print("Enter AM/PM:  ");
        reader.nextLine();
        String endingTOD = reader.nextLine();

        System.out.println();

        int hours;
        int minutes = endingMin - startingMin;
        String Am = "am" ;
        String Pm = "pm" ;

       if (endingTOD.equalsIgnoreCase(startingTOD) &&  minutes <  0  )
       {
           hours = (endingHour - startingHour) -1 ;
           minutes = minutes + 60 ;
           System.out.println(hours +  " "  + minutes);

        }
     else  if (endingHour > startingHour&& endingTOD.equalsIgnoreCase(startingTOD) &  minutes > 0  )
       {
           hours = endingHour - startingHour;
           System.out.println(hours + " " + minutes);
        }
      else  if (endingHour > startingHour && endingTOD.equalsIgnoreCase(startingTOD) && minutes == 0  )
     {
         hours = (endingHour-startingHour);
         minutes = 0;
         System.out.println(hours + " " + minutes);
     }
   else  if (endingHour < startingHour && endingTOD.equalsIgnoreCase(startingTOD) && minutes == 0  )
     {
         hours = (endingHour-startingHour) + 12;
         minutes = 0;
         System.out.println(hours + " " + minutes);
     }
   else if ( endingHour==startingHour && minutes == 0)
   {
        hours = 12;
        minutes = 0;
        System.out.println(hours + " " + minutes);
    }
    else if (( endingTOD.equalsIgnoreCase(Pm) && startingTOD.equalsIgnoreCase(Am)) && minutes > 0)
    {
        hours = (endingHour - startingHour) + 12;
        System.out.println(hours + " " + minutes);
    }

 else if  (( endingTOD.equalsIgnoreCase(Pm) && startingTOD.equalsIgnoreCase(Am)) && minutes < 0)
       {
           hours = (endingHour - startingHour) -1 ;
           minutes = minutes + 60 ;
           System.out.println(hours +  " "  + minutes);

        }
 else if (endingHour > startingHour && ( endingTOD.equalsIgnoreCase(Pm) && startingTOD.equalsIgnoreCase(Am)) && minutes == 0)
    {
        hours = (endingHour-startingHour) + 12;
        minutes = 0;
       System.out.println(hours +  " "  + minutes);
    }
    else if (endingHour < startingHour &&( endingTOD.equalsIgnoreCase(Pm) && startingTOD.equalsIgnoreCase(Am)) && minutes == 0)
    {
        hours = (endingHour - startingHour) +24;
        minutes = 0;
       System.out.println(hours +  " "  + minutes);
    }
   else if (endingHour < startingHour &&( endingTOD.equalsIgnoreCase(Pm) && startingTOD.equalsIgnoreCase(Am)) && minutes > 0)
    {
        hours = (endingHour - startingHour) + 2;
        System.out.println(hours + " " + minutes);
    }
        }

2 个答案:

答案 0 :(得分:1)

鉴于您无法使用Java Calendar API,您的方法虽然不是非常模块化,但乍一看看起来很合理。魔鬼在细节中。

日期时间计算的技巧是所有角落情况。这就是为什么没有人想编写和维护这样的东西,甚至Sun / Oracle一次又一次地弄错了。

证明您的代码适用于所有条件都很困难。您最好减少范围并降低要求。 12或24小时钟?如果24小时,我们从0h或1h开始吗?我们是否跨越了几天?我们预计会过夜吗?等

但你的任务是以模12或24的方式比较小时数(除非你的要求说你不需要&#34;翻转&#34;或跨越12或24小时的界限。)真正的诀窍是将小时视为一系列栅栏柱和轨道,并计算轨道。一次性错误将成为你在这里存在的祸根。

我的建议是至少使用Java Calendar API来仔细检查结果。

答案 1 :(得分:0)

不是试图重新发明轮子并自己实现日期减法逻辑,而是尝试覆盖所有角落情况,您可以利用内置的Java Date Arithmetic。

像这样(将此代码复制到TimeDifference.java并运行):

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
import java.util.Calendar;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

public class TimeDifference {

    public static void elapsedTime() {
        Scanner reader = new Scanner(System.in);

        System.out.print("Enter the beginning hour: ");
        int startingHour = reader.nextInt();

        System.out.print("Enter the beginning minute(s): ");
        int startingMin = reader.nextInt();

        System.out.print("Enter AM/PM: ");
        reader.nextLine();
        String startingTOD = reader.nextLine();



        String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
        // if no ids were returned, something is wrong. get out.
        if (ids.length == 0)
            System.exit(0);

        // create a Pacific Standard Time time zone
        SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);

        // set up rules for daylight savings time
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY,
                2 * 60 * 60 * 1000);

        // create a GregorianCalendar with the Pacific Daylight time zone
        // and the current date and time
        Calendar startingCalendar = new GregorianCalendar(pdt);
        Calendar endingCalendar = new GregorianCalendar(pdt);
        Date trialTime = new Date();
        startingCalendar.setTime(trialTime);
        endingCalendar.setTime(trialTime);

        startingCalendar.set(java.util.Calendar.HOUR, startingHour);
        startingCalendar.set(java.util.Calendar.MINUTE, startingMin);

        if (startingTOD.equalsIgnoreCase("AM")) {
            startingCalendar.set(java.util.Calendar.AM_PM, 0);
        } else if (startingTOD.equalsIgnoreCase("PM")) {
            startingCalendar.set(java.util.Calendar.AM_PM, 1);
        } else {
            System.out.println("invalid starting AM/PM. exiting..");
            System.exit(-1);
        }

        System.out.print("Enter the ending hour: ");
        int endingHour = reader.nextInt();

        System.out.print("Enter the ending minute(s): ");
        int endingMin = reader.nextInt();

        System.out.print("Enter AM/PM:  ");
        reader.nextLine();
        String endingTOD = reader.nextLine();

        System.out.println();

        // get the supported ids for GMT-08:00 (Pacific Standard Time)

        endingCalendar.set(java.util.Calendar.HOUR, endingHour);
        endingCalendar.set(java.util.Calendar.MINUTE, endingMin);

        if (endingTOD.equalsIgnoreCase("AM")) {
            endingCalendar.set(java.util.Calendar.AM_PM, 0);
        } else if (endingTOD.equalsIgnoreCase("PM")) {
            endingCalendar.set(java.util.Calendar.AM_PM, 1);
        } else {
            System.out.println("invalid ending AM/PM. exiting..");
            /* Exit program */
            System.exit(-1);
        }

        long startingTimeMillis = startingCalendar.getTimeInMillis();
        long endingTimeMillis = endingCalendar.getTimeInMillis();
        long timeDifferenceMillis = endingTimeMillis - startingTimeMillis;

        System.out.println(String.format("Time difference between starting and ending time (in minutes and hours): %d hours, %d minutes", 
                TimeUnit.MILLISECONDS.toHours(timeDifferenceMillis),
                TimeUnit.MILLISECONDS.toMinutes(timeDifferenceMillis) - 
                TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDifferenceMillis))
            ));

        reader.close();
    }

    public static void main(String[] args) {
        elapsedTime();
    }

}