在java中计算月份和时差?

Posted

技术标签:

【中文标题】在java中计算月份和时差?【英文标题】:Calculate month and time difference in java? 【发布时间】:2017-09-24 19:34:27 【问题描述】:

我有这个代码来计算月份和时差,但是这个代码给出了错误的输出 当我测试这段代码时,它计算的 3 个月甚至实际月差为 1,并且在时间相同的情况下,请帮忙看看这段代码的问题在哪里......

    public static void updateLinkDownTimeDate(ObjectId TimeDateId, TimeDatePojo TimeDatePojo) 
            try 
                List<DBObject> array = new ArrayList<>();
                BasicDBObject match = new BasicDBObject();
                match.put("_id", TimeDateId);
                DBCollection collection = new MongoSetup().getDBCollection("TimeDate");
                DBObject obj = TimeDatePojo.bsomFromPojo();
                String newId = (String) obj.get("linkId");
                SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
                String startDate = dates.format(obj.get("startDate"));
                String endDate = dates.format(obj.get("endDate"));
                Date SD = dates.parse(startDate);
                Date ED = dates.parse(endDate);
                Calendar cal = Calendar.getInstance();
                cal.setTime(SD);
                int month = cal.get(Calendar.MONTH);
                int year = cal.get(Calendar.YEAR);

                String startTime = (String) obj.get("startTime"); //present start time
                SimpleDateFormat forms = new SimpleDateFormat("dd-MM-yyyy");
                SimpleDateFormat form = new SimpleDateFormat("HH:mm:ss");
                Calendar currentStartDateCalendar = Calendar.getInstance();
                currentStartDateCalendar.setTime(SD);
                int currentSDate = currentStartDateCalendar.get(Calendar.DATE);
                int currentStartMonth = currentStartDateCalendar.get(Calendar.MONTH);
                int currentStartYear = currentStartDateCalendar.get(Calendar.YEAR);
                Date STs = form.parse(startTime);
                Calendar presentStartTime = Calendar.getInstance();
                presentStartTime.setTime(STs);
                int currentHour = presentStartTime.get(Calendar.HOUR);
                int currentMin = presentStartTime.get(Calendar.MINUTE);
                int currentSec = presentStartTime.get(Calendar.SECOND);
                currentStartDateCalendar.set(currentStartYear, currentStartMonth, currentSDate, currentHour, currentMin, currentSec);
                Date PSDate = currentStartDateCalendar.getTime();

                String endTime = (String) obj.get("endTime");  //present end time
                Date ETs = form.parse(endTime);
                Calendar currentEndDateCalender = Calendar.getInstance();
                currentEndDateCalender.setTime(ED);
                int currentEDate = currentEndDateCalender.get(Calendar.DATE);
                int currentEndMonth = currentEndDateCalender.get(Calendar.MONTH);
                int currentEYear = currentEndDateCalender.get(Calendar.YEAR);
                Calendar presentEndTime = Calendar.getInstance();
                presentEndTime.setTime(ETs);
                int currentEndHour = presentEndTime.get(Calendar.HOUR);
                int currentEndMin = presentEndTime.get(Calendar.MINUTE);
                int currentEndSec = presentEndTime.get(Calendar.SECOND);
                currentEndDateCalender.set(currentEYear, currentEndMonth, currentEDate, currentEndHour, currentEndMin, currentEndSec);
                Date PEDate = currentEndDateCalender.getTime();
                BasicDBObject getSavedDate = new BasicDBObject();
                getSavedDate.append("_id", linkDownTimeDateId);
                getSavedDate.append("linkId", newId);
                DBObject seeSaved = collection.findOne(getSavedDate);
                Date savedSDate = (Date) seeSaved.get("startDate");
                Date savedEDate = (Date) seeSaved.get("endDate");
                String savedStartTime = (String) seeSaved.get("startTime");
                String savedEndTime = (String) seeSaved.get("endTime");
                Date SSD = null;
                Date SED = null;
                if (savedSDate.compareTo(SD) == 0 && savedEDate.compareTo(ED) == 0) 
                    Calendar saveStartTimeCalendar = Calendar.getInstance();
                    saveStartTimeCalendar.setTime(savedSDate);
                    int savedYear = saveStartTimeCalendar.get(Calendar.YEAR);
                    int savedMonth = saveStartTimeCalendar.get(Calendar.MONTH);
                    int savedDate = saveStartTimeCalendar.get(Calendar.DATE);
                    Date SSTs = form.parse(savedStartTime);
                    Calendar savedStartTimeCal = Calendar.getInstance();
                    savedStartTimeCal.setTime(SSTs);
                    int hour = savedStartTimeCal.get(Calendar.HOUR);
                    int mins = savedStartTimeCal.get(Calendar.MINUTE);
                    int secs = savedStartTimeCal.get(Calendar.SECOND);
                    saveStartTimeCalendar.set(savedYear, savedMonth, savedDate, hour, mins, secs);
                    SSD = saveStartTimeCalendar.getTime();
                    Calendar saveEndTimeCalendar = Calendar.getInstance();
                    saveStartTimeCalendar.setTime(savedEDate);
                    int savedEndYear = saveEndTimeCalendar.get(Calendar.YEAR);
                    int savedEndMonth = saveEndTimeCalendar.get(Calendar.MONTH);
                    int savedEndDates = saveEndTimeCalendar.get(Calendar.DATE);
                    Date ESTs = form.parse(savedEndTime);
                    Calendar savedEndTimeCal = Calendar.getInstance();
                    savedEndTimeCal.setTime(ESTs);
                    int endhour = savedStartTimeCal.get(Calendar.HOUR);
                    int endmins = savedStartTimeCal.get(Calendar.MINUTE);
                    int endsecs = savedStartTimeCal.get(Calendar.SECOND);
                    saveEndTimeCalendar.set(savedEndYear, savedEndMonth, savedEndDates, endhour, endmins, endsecs);
                    SED = saveEndTimeCalendar.getTime();
                 else if (savedSDate.compareTo(SD) == -1 || savedEDate.compareTo(ED) == -1) 
                    Calendar saveStartTimeCalendar = Calendar.getInstance();
                    saveStartTimeCalendar.setTime(SD);
                    int savedYear = saveStartTimeCalendar.get(Calendar.YEAR);
                    int savedMonth = saveStartTimeCalendar.get(Calendar.MONTH);
                    int savedDate = saveStartTimeCalendar.get(Calendar.DATE);
                    Date SSTs = form.parse(savedStartTime);
                    Calendar savedStartTimeCal = Calendar.getInstance();
                    savedStartTimeCal.setTime(SSTs);
                    int hour = savedStartTimeCal.get(Calendar.HOUR);
                    int mins = savedStartTimeCal.get(Calendar.MINUTE);
                    int secs = savedStartTimeCal.get(Calendar.SECOND);
                    saveStartTimeCalendar.set(savedYear, savedMonth, savedDate, hour, mins, secs);
                    SSD = saveStartTimeCalendar.getTime();
                    Calendar saveEndTimeCalendar = Calendar.getInstance();
                    saveStartTimeCalendar.setTime(ED);
                    int savedEndYear = saveEndTimeCalendar.get(Calendar.YEAR);
                    int savedEndMonth = saveEndTimeCalendar.get(Calendar.MONTH);
                    int savedEndDates = saveEndTimeCalendar.get(Calendar.DATE);
                    Date ESTs = form.parse(savedEndTime);
                    Calendar savedEndTimeCal = Calendar.getInstance();
                    savedEndTimeCal.setTime(ESTs);
                    int endhour = savedStartTimeCal.get(Calendar.HOUR);
                    int endmins = savedStartTimeCal.get(Calendar.MINUTE);
                    int endsecs = savedStartTimeCal.get(Calendar.SECOND);
                    saveEndTimeCalendar.set(savedEndYear, savedEndMonth, savedEndDates, endhour, endmins, endsecs);
                    SED = saveEndTimeCalendar.getTime();
                
                List<DBObject> lists = (List<DBObject>) seeSaved.get("linkDownTime");
                int down = 0;
                for (DBObject dating : lists) 
                    down = (int) dating.get("downTime"); //saved down time
                
                String startHour = "00:00:00";
                String endHour = "24:00:00";
                long minutesInOneDay = 1440;
                int numberOfDays = 0;
                long dateDifference = 0l;
                int totalCalculatedMins = 0;
                try 
                    dateDifference = ED.getTime() - SD.getTime();
                    long days = dateDifference / (24 * 60 * 60 * 1000);
                    numberOfDays = (int) days;
                    if (numberOfDays == 0) 
                        int min = (int) minutesInOneDay;
                        SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");
                        Date parsedStartTime = format2.parse(startTime);
                        Date parsedEndTime = format2.parse(endTime);
                        Date parsedOriginalStartHour = format2.parse(startHour);
                        Date parsedOriginalEndHour = format2.parse(endHour);
                        long excludeStartTime = parsedOriginalEndHour.getTime() - parsedStartTime.getTime();
                        long excludedStartMins = minutesInOneDay - (excludeStartTime / (60 * 1000));
                        int excludedMins = (int) excludedStartMins;
                        long excludeEndTime = parsedEndTime.getTime() - parsedOriginalStartHour.getTime();
                        long excludeEndMins = 1440 - (excludeEndTime / (60 * 1000));
                        int excludeMins2 = (int) excludeEndMins;
                        long calculation = min - excludedMins - excludeMins2;
                        totalCalculatedMins = (int) calculation;
                     else 
                        long minuetes = (minutesInOneDay * numberOfDays);
                        int min = (int) minuetes;
                        SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");
                        Date parsedStartTime = format2.parse(startTime);
                        Date parsedEndTime = format2.parse(endTime);
                        Date parsedOriginalStartHour = format2.parse(startHour);
                        Date parsedOriginalEndHour = format2.parse(endHour);
                        long excludeStartTime = parsedOriginalEndHour.getTime() - parsedStartTime.getTime();
                        long excludedStartMins = excludeStartTime / (60 * 1000);
                        int excludedMins = (int) excludedStartMins;
                        long excludeEndTime = parsedEndTime.getTime() - parsedOriginalStartHour.getTime();
                        long excludeEndMins = 1440 + (-(excludeEndTime / (60 * 1000)));
                        int excludeMins2 = (int) excludeEndMins;
                        long calculation = min + excludedMins - excludeMins2;
                        totalCalculatedMins = (int) calculation;
                    
                 catch (Exception e) 
                    System.out.println("Exception being :-" + e);
                
                DBObject sub = new BasicDBObject();
                sub.put("linkId", newId);
                sub.put("year", year);
                sub.put("month", month);
                sub.put("downTime", totalCalculatedMins);
                array.add(sub);
                obj.put("linkDownTime", array);
                BasicDBObject update = new BasicDBObject();
                update.put("$set", obj);
                collection.update(match, update, true, false);
                BasicDBObject newQuery = new BasicDBObject("linkId", obj.get("linkId"))
                        .append("startDate", obj.get("startDate"))
                        .append("endDate", obj.get("endDate"));
                DBObject findNewQuery = collection.findOne(newQuery);
                DBCollection collection2 = new MongoSetup().getDBCollection("linkTotalDownTime");
                List<DBObject> list = (List<DBObject>) findNewQuery.get("linkDownTime");
                for (DBObject data : list) 
                    String linkId = (String) data.get("linkId");
                    int years = (int) data.get("year");
                    int months = (int) data.get("month");
                    int downTime = (int) data.get("downTime"); // current downTime 

                    BasicDBObject look = new BasicDBObject();
                    look.append("linkID", linkId).append("Year", year).append("month", month);
                    DBObject findData = collection2.findOne(look);
                    int dataget = (int) findData.get("totaldownTime"); //totaldowntime 
                    int finalValue = 0;
                    int finalTotalValue = 0;
                    if (collection2.count() == 1) 
                        if (PSDate.compareTo(SSD) == 1) 
                            if (downTime > down) 
                                finalValue = down - downTime;
                                finalTotalValue = (int) (dataget - finalValue);
                             else if (down > downTime) 
                                finalValue = down - downTime;
                                finalTotalValue = (int) (dataget - finalValue);
                            
                         else if (PSDate.compareTo(SSD) == -1) 
                            if (downTime > down) 
                                finalValue = downTime - down;
                                finalTotalValue = (int) (dataget + finalValue);
                             else if (down > downTime) 
                                finalValue = down - downTime;
                                finalTotalValue = (int) (dataget + finalValue);
                            
                         else if (PEDate.compareTo(SED) == 1) 
                            if (downTime > down) 
                                finalValue = downTime - down;
                                finalTotalValue = (int) (dataget + finalValue);
                             else if (down > downTime) 
                                finalValue = down - downTime;
                                finalTotalValue = (int) (dataget + finalValue);
                            
                         else if (PEDate.compareTo(SED) == -1) 
                            if (downTime > down) 
                                finalValue = downTime - down;
                                finalTotalValue = (int) (dataget - finalValue);
                             else if (down > downTime) 
                                finalValue = down - downTime;
                                finalTotalValue = (int) (dataget - finalValue);
                            
                        
                     else if (collection2.count() > 1) 
                        if (PSDate.compareTo(SSD) == 1) 
                            if (downTime > down) 
                                finalValue = downTime - down;
                                finalTotalValue = (int) (dataget - finalValue);
                             else if (down > downTime) 
                                finalValue = down - downTime;
                                finalTotalValue = (int) (dataget - finalValue);
                            
                         else if (PSDate.compareTo(SSD) == -1) 
                            if (downTime > down) 
                                finalValue = downTime - down;
                                finalTotalValue = (int) (dataget + finalValue);
                             else if (down > downTime) 
                                finalValue = down - downTime;
                                finalTotalValue = (int) (dataget + finalValue);
                            
                         else if (PEDate.compareTo(SED) == 1) 
                            if (downTime > down) 
                                finalValue = downTime - down;
                                finalTotalValue = (int) (dataget + finalValue);
                             else if (down > downTime) 
                                finalValue = down - downTime;
                                finalTotalValue = (int) (dataget + finalValue);
                            
                         else if (PEDate.compareTo(SED) == -1) 
                            if (downTime > down) 
                                finalValue = downTime - down;
                                finalTotalValue = (int) (dataget - finalValue);
                             else if (down > downTime) 
                                finalValue = down - downTime;
                                finalTotalValue = (int) (dataget - finalValue);
                            
                        
                    
                    BasicDBObject update_two = new BasicDBObject();
                    update_two.put("linkID", linkId);
                    update_two.put("Year", years);
                    update_two.put("month", months);
                    update_two.put("totaldownTime", finalTotalValue);
                    collection2.update(findData, update_two, true, false);
                
                System.out.println("Updated Successfully ...");
             catch (Exception ex) 
                ex.printStackTrace();
            
        

【问题讨论】:

您应该遵循@LukeJanyga 的建议并使用java.time 框架。停止使用原始 java.util.Date 对象并开始使用 LocalDateTime、LocalDate、LocalTime 等。 你能告诉我代码中的错误在哪里,为什么它没有给出正确的月差和时差? 我现在没有空来看看你的代码。对您来说最好的方法是切换到 java 时间:因为您可以更快地工作,从而减少代码行数。 看看java time javadoc和this article。 【参考方案1】:

请使用目前 Java 的标准 JSR-310(称为 ThreeTen)。它提供了像 DurationChronoUnit 这样的类,其中包含所有必要的工具。

例如ChronoUnit.MONTHS.between() 将计算两个日期之间的跨度(以月为单位)

【讨论】:

【参考方案2】:
String calculateTime(String strDate) throws ParseException 

    String result = "";
    SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMHHmm");
    Date currDate = new Date();
    String date = dateFormat.format(currDate);

    currDate = dateFormat.parse(date);
    Date postDate = dateFormat.parse(strDate);

    //calculate day diff
    long timeDiff = currDate.getTime() - postDate.getTime();
    long daysDiff = TimeUnit.MILLISECONDS.toDays(timeDiff);
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.setTime(postDate);

    if (daysDiff == 1) 


        result = "yesterday";
        result = result + " at " + getHour(calendar.get(Calendar.HOUR)) + ":"
                + setPrefix(calendar.get(Calendar.MINUTE))+ " " + getAM_PM(calendar.get(Calendar.AM_PM));

     else if (daysDiff > 1) 

        result = calendar.get(Calendar.DATE) + " " + getMonthForInt(calendar.get(Calendar.MONTH));
        result = result + " at " + getHour(calendar.get(Calendar.HOUR)) + ":"
                + setPrefix(calendar.get(Calendar.MINUTE)) + " " + getAM_PM(calendar.get(Calendar.AM_PM));

     else 

         long minDiff = TimeUnit.MILLISECONDS.toMinutes(timeDiff);


        if (minDiff == 0) 

            result = "just now";
         else if (minDiff < 60) 

            if (minDiff == 1) 

                result = minDiff + " min ago";
             else if(minDiff > 1)  
                result = minDiff + " mins ago";
            

         else 

            long hourDiff = TimeUnit.MILLISECONDS.toHours(timeDiff);

            if (hourDiff == 1) 

                result = hourDiff + " hr ago";
             else if(hourDiff > 1)

                result = hourDiff + " hrs ago";

            

        

    

    return result;

【讨论】:

以上是关于在java中计算月份和时差?的主要内容,如果未能解决你的问题,请参考以下文章

仅在几个月和几天计算时差

计算java中月份和年份的总天数[关闭]

Python中特定年份的时差

java 中 判断两个日期月份的差,后面没有时分秒.比如2013-07-03与2013-09-03 返回值为2

js如何计算两个日期的月份差?

java 实现打印当前月份的日历