java中计算月份和时差?

a6b3iqyw  于 2023-05-21  发布在  Java
关注(0)|答案(3)|浏览(121)

我有这个代码计算月份和时间差,但这个代码是错误的输出其计算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();
            }
        }
mf98qq94

mf98qq941#

请使用JSR-310(称为ThreeTen),这是目前Java的标准。它提供了像DurationChronoUnit这样的类,其中包含所有必要的工具。
例如,ChronoUnit.MONTHS.between()将计算2个日期之间的跨度(以月为单位)

sg3maiej

sg3maiej2#

java.time

只使用 * java.time * 类,不要使用有严重缺陷的遗留类,如DateCalendarSimpleDateFormat
使用DateTimeFormatter定义与输入匹配的格式模式。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;

解析为LocalDate

LocalDate ld = LocalDate.parse( input , f ) ;

以标准ISO 8601格式生成表示该值的文本。

String output = ld.toString() ;

以自定义格式生成表示该值的文本。

String output = ld.format( f ) ;
bqf10yzr

bqf10yzr3#

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

相关问题