日期剩余的天数显示不正确

时间:2018-09-12 10:29:41

标签: android date java-time date-difference android-date

好,所以我创建了一个函数来显示直到将来某个日期的天数...直到天数超过9天才是正确的..如果超过该天数似乎显示一个随机数天数...请在下面查看我的代码:

   public String daysTillExpire() {
        String daysLeft = "";
        int position = 0 ;
        String inputDateString = UIDM.get(position).date;
        Calendar calCurr = Calendar.getInstance();
        Calendar day = Calendar.getInstance();


        try {
            day.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(inputDateString));

        } catch (ParseException e) {
            e.printStackTrace();
        }

            if (day.after(calCurr)) {

                String noumberOfDays = "Days left: " + (day.get(Calendar.DAY_OF_MONTH) - (calCurr.get(Calendar.DAY_OF_MONTH)));

                daysLeft = UIDM.get(position).date + "\n(" + noumberOfDays+")" ;

            }

            else if (day.before(calCurr)) {
                daysLeft = "Key Expired";
            return daysLeft; }
        return daysLeft;
    }

UIDM是一个包含信息的数据模型... String inputDateString = UIDM.get(position).date;返回值01-10-2018 23:59

4 个答案:

答案 0 :(得分:4)

java.time

java.time,现代的Java日期和时间API,具有用于计算两个日期之间的天数的方法。因此,请您自己进行计算。容易出错。

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu H:mm");
    String inputDateString = "01-10-2018 23:59";
    LocalDate today = LocalDate.now(ZoneId.of("Pacific/Auckland"));
    LocalDate expiration = LocalDate.parse(inputDateString, dateFormatter);
    if (expiration.isAfter(today)) {
        String numberOfDays = "Days left: " + ChronoUnit.DAYS.between(today, expiration);
        System.out.println(numberOfDays);
    }

立即运行此代码段(已经在新西兰,9月13日),我得到了以下输出:

  

剩余天数:18

如果不是太平洋时间/奥克兰,请替换您的正确时区。

LaVepe的答案已经很好地,正确地解释了您的代码出了什么问题,所以我不再重复。

您使用的日期和时间类-CalendarSimpleDateFormat-早已过时,并且设计总是很差。有一种方法可以让Calendar一次计算1天的天数,但这种方法不太适合。 SimpleDateFormat因给许多程序员带来麻烦而臭名昭著。我建议您完全避免使用这些类,而改用java.time。

问题:我可以在Android上使用java.time吗?

是的,java.time在较新的Android设备上都能很好地工作。它只需要至少Java 6

  • 在Java 8和更高版本以及较新的Android设备上(我被告知,从API级别26开始),内置了现代API。
  • 在Java 6和7中,获得ThreeTen Backport,即新类的backport(JSR 310的ThreeTen;请参见底部的链接)。
  • 在(较旧的)Android上,使用Android版本的ThreeTen Backport。叫做ThreeTenABP。并确保您使用子包从org.threeten.bp导入日期和时间类。

链接

答案 1 :(得分:1)

请注意,Calendar.DAY_OF_MONTH返回1到31之间的月份。

因此它将计算两天之间的差额(1到31之间的数字),就像它们在同一个月一样

我建议使用时间戳,然后将结果从毫秒转换为这样的天数:

long oneDay = 24 * 60 * 60 * 1000;  // in milliseconds
long diff = day.getTime().getTime() - calCurr.getTime().getTime();
long numberOfDays = diff / oneDay;

然后您可以使用String将其更改为Long.toString(numberOfDays)

答案 2 :(得分:1)

尝试此方法

/**
         *  
         * @param token
         * @param date1 present date
         * @param date2 future date 
         * @return diff
         */
        public float dateDiff(String token,Date date1,Date date2){

            float diff=0;
            //different date might have different offset
            Calendar cal1=Calendar.getInstance(); 
            Calendar cal2=Calendar.getInstance();
            cal1.setTime(date1);          
            long ldate1 = date1.getTime() + cal1.get(Calendar.ZONE_OFFSET) + cal1.get(Calendar.DST_OFFSET);

            if(date2==null)
                cal2.setTime(new Date());
            else
                cal2.setTime(date2);
            long ldate2 = date2.getTime() + cal2.get(Calendar.ZONE_OFFSET) + cal2.get(Calendar.DST_OFFSET);

            // Use integer calculation, truncate the decimals
            int hr1   = (int)(ldate1/3600000); //60*60*1000
            int hr2   = (int)(ldate2/3600000);

            int days1 = hr1/24;
            int days2 = hr2/24;
            int dateDiff  = days2 - days1;
            int yearDiff  = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR); 
            float monthDiff = yearDiff * 12 + cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
            System.out.println("monthDiff 1" +monthDiff);
            System.out.println(" days:  ;;;;222  "+dateDiff);
            float fbm = dateDiff ; 

            fbm = (float) MasterLibraryFunction.doubRound(fbm /30,2) ;

                if(token.equals("d"))
            {
                diff=dateDiff;
                System.out.println(" days:  ;;;;  "+dateDiff);
            }
            else if(token.equals("m"))
            {
                //diff= monthDiff;
                diff =fbm;
                System.out.println(" diff ---------->:  ;;;;  "+fbm);

            }

    /*******day wise diff *******/      


            return diff;
        }



/**
     * @category Decimal point round
     * @param  val
     * @param  places
     * @return Rounded Value to given place
     */
    public static double doubRound(double val, int places) {
        long factor = (long)Math.pow(10,places);
        val = val * factor;
        long tmp = Math.round(val);
        return (double)tmp / factor;
    }

答案 3 :(得分:1)

要获取两天之间的间隔天,您可以这样做:

public long daysTillExpire() {

    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
    String dateInString = "01-10-2018 23:59";
    Date date = null;
    try {
        date = sdf.parse(dateInString);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    Calendar expiredCalendar = Calendar.getInstance();
    expiredCalendar.setTime(date);

    long msDiff = expiredCalendar.getTimeInMillis() - Calendar.getInstance().getTimeInMillis();
    long daysDiff = TimeUnit.MILLISECONDS.toDays(msDiff); 

    return daysDiff;
}

以上功能已成功测试,请根据您的要求进行修改。