计算java中的月份和时间差异?

时间:2017-04-27 06:45:46

标签: java servlets dao

我有这个代码用于计算月份和时间差异,但此代码提供了错误的输出 它计算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();
            }
        }

2 个答案:

答案 0 :(得分:1)

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

E.g。 ChronoUnit.MONTHS.between()将计算两个月之间的跨度

答案 1 :(得分:-1)

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