如何在 Android 中的 2 个日期之间进行减法?

我从日期选择器中选择了一个日期,从当前系统时间中选择了另一个日期。当我想减去 2 个日期时,其中一个是 2000 年之前的日期,我得到了一些无效的答案。我该如何解决?


public class Duration {

    private int year,month,day,hour,min,seconds;


    public Duration(long endTime, long startTime){

        Calendar calendar1=new GregorianCalendar();

        calendar1.setTimeInMillis(endTime);

        Calendar calendar=new GregorianCalendar();

        calendar.setTimeInMillis(startTime);

        this.year=calendar1.get(Calendar.YEAR)-calendar.get(Calendar.YEAR);

        this.month=calendar1.get(Calendar.MONTH)-calendar.get(Calendar.MONTH);

        this.day=calendar1.get(Calendar.DAY_OF_MONTH)-calendar.get(Calendar.DAY_OF_MONTH);

        this.hour=calendar1.get(Calendar.HOUR)-calendar.get(Calendar.HOUR);

        this.min=calendar1.get(Calendar.MINUTE)-calendar.get(Calendar.MINUTE);

        this.seconds=calendar1.get(Calendar.SECOND)-calendar.get(Calendar.SECOND);

        System.out.println(toString());

    }


    public int getDay() {

        return day;

    }


    public int getHour() {

        return hour;

    }


    public int getMin() {

        return min;

    }


    public int getMonth() {

        return month;

    }


    public int getSeconds() {

        return seconds;

    }


    public int getYear() {

        return year;

    }


    @Override

    public String toString() {

        return year+" "+month+" "+day+" "+hour+" "+min+" "+seconds;

    }

}

当我想从当前时间减去 1998/2/jan 的日期时,我得到以下结果:


-1879 1 3 10 24 34

年份不正确。


烙印99
浏览 214回答 3
3回答

潇湘沐

方法:1 try {    DateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");    Date date1 = new java.util.Date();    Date date2 = df.parse("04-02-2019 12:00:00");    long diff = date2.getTime() - date1.getTime();    Calendar cal = Calendar.getInstance();    cal.setTimeInMillis(diff);    int year = cal.get(Calendar.YEAR);    Log.e("Diff Year" , year+ " --" + diff);    Log.e("Diff Value" , date1.getTime() + " -- " + date2.getTime() + " --" + diff);} catch (ParseException e){    Log.e("Diff Value", "Exception", e.getMessage().toString());}方法:2LocalDate d1 = LocalDate.parse("2017-04-02", DateTimeFormatter.ISO_LOCAL_DATE);LocalDate d2 = LocalDate.parse("2018-04-04", DateTimeFormatter.ISO_LOCAL_DATE);Duration dateDifference = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());long dayDifference = dateDifference.toDays();减去两个日期并在对象中添加差异值 Calendar并从其对象中检索年份值。

哔哔one

LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());long diffDays = diff.toDays();您将获得长格式的天数。另请参阅 Mark Byers 的这个答案。

尚方宝剑之说

LocalDate&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Represent a date-only value, without time-of-day and without time zone..of( 1999 , 1 , 23 )&nbsp; &nbsp; // Use factory methods to instantiate rather than constructors, in the *java.time* classes..minusWeeks( 12 )&nbsp; &nbsp; &nbsp; &nbsp;// Do date-math with `plus…` and `…minus` methods..toString()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Generate text as a `String` object with text representing the date value in standard ISO 8601 format: YYYY-MM-DD请参阅在 IdeOne.com 上实时运行的代码。1998-10-31避免遗留的日期时间类永远不要使用Calendar或Date类。那些可怕的类在几年前被java.time类所取代。LocalDate该类LocalDate表示没有时间、没有时区或从 UTC 偏移的仅日期值。时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因区域而异。例如,法国巴黎午夜过后几分钟是新的一天,而魁北克蒙特利尔仍然是“昨天” 。如果未指定时区,JVM 会隐式应用其当前默认时区。该默认值可能会在运行时(!)期间随时更改,因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。以、或等格式指定适当的时区名称。永远不要使用 2-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。Continent/RegionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTISTZoneId z = ZoneId.of( "America/Montreal" ) ;&nbsp;&nbsp;LocalDate today = LocalDate.now( z ) ;如果你想使用 JVM 的当前默认时区,请求它并作为参数传递。如果省略,代码会变得模棱两可,因为我们不确定您是否打算使用默认值,或者您是否像许多程序员一样没有意识到这个问题。ZoneId z = ZoneId.systemDefault() ;&nbsp; // Get JVM’s current default time zone.或指定日期。您可以通过数字设置月份,1 月至 12 月的编号为 1-12。LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;&nbsp; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.或者,更好的是,使用Month预定义的枚举对象,一年中的每个月一个。提示:Month在整个代码库中使用这些对象,而不是仅仅使用整数,以使您的代码更具自文档性、确保有效值并提供类型安全。Year&同上YearMonth。LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;Period要以年-月-日表示时间跨度,请使用Period.Period p = Period.ofDays( 5 ) ;日期时间数学您可以通过调用and方法在java.time中执行日期时间值的加法和减法。plus…minus…LocalDate later = ldt.plus( p ) ;Duration如果您想用天(24 小时的时间块,与日历无关)、小时、分钟、秒和小数秒来表示时间跨度,请使用Duration.年您的问题不清楚,但似乎是关于 2000 年。java.time类的那一年没有什么特别之处。您可以查询java.time类的年份值。int year = ld.getYear() ;if( year < 2000 ) { … }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java