在android中如何获得2个日期之间的减法?

eoxn13cs  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(294)

我从日期选取器中选取了一个日期,从当前系统时间中选取了另一个日期。当我想减去其中一个是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年1月2日的某个日期时,我得到以下结果:

-1879 1 3 10 24 34

年份不正确。

tquggr8v

tquggr8v1#

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();

您将获得长格式的天数。也可以参考马克·拜尔斯的回答。

kxeu7u2r

kxeu7u2r2#

热释光;博士

LocalDate               // Represent a date-only value, without time-of-day and without time zone.
.of( 1999 , 1 , 23 )    // Use factory methods to instantiate rather than constructors, in the *java.time* classes.
.minusWeeks( 12 )       // Do date-math with `plus…` and `…minus` methods.
.toString()             // 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 类表示一个仅限日期的值,不包含一天中的时间,也不包含时区或utc的偏移量。
时区是决定日期的关键。在任何一个特定的时刻,世界各地的日期因地区而异。例如,在法国巴黎,午夜过后几分钟是新的一天,而在蒙特勒仍然是“昨天”é阿尔曲é贝克。
如果未指定时区,jvm将隐式应用其当前默认时区。在运行时(!)期间,该默认值可能随时更改,所以你的结果可能会有所不同。最好将所需/预期时区显式指定为参数。
以以下格式指定正确的时区名称 Continent/Region ,例如 America/Montreal , Africa/Casablanca ,或 Pacific/Auckland . 切勿使用2-4个字母的缩写,例如 EST 或者 IST 因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

如果您想使用jvm的当前默认时区,那么请求它并将其作为参数传递。如果省略,代码将变得模棱两可,我们无法确定您是否打算使用默认值,或者您是否像许多程序员一样不知道这个问题。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

或指定日期。你可以用数字来设定月份,1-12月份的数字是1-12。

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // 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 p = Period.ofDays( 5 ) ;

日期时间数学

通过调用 plus… 以及 minus… 方法。

LocalDate later = ldt.plus( p ) ;

持续时间

如果要用天(24小时的时间块,与日历无关)、小时、分钟、秒和分秒来表示时间跨度,请使用 Duration .

你的问题不清楚,但好像是2000年的事。当年的java.time类没有什么特别之处。
您可以查询java.time类的年份值。

int year = ld.getYear() ;
if( year < 2000 ) { … }

关于java.time

java.time框架内置于Java8及更高版本中。这些类取代了旧的遗留日期时间类,例如 java.util.Date , Calendar , & SimpleDateFormat .
现在处于维护模式的joda time项目建议迁移到java.time类。
要了解更多信息,请参阅oracle教程。和搜索堆栈溢出的许多例子和解释。规格为jsr 310。
您可以直接与数据库交换java.time对象。使用符合jdbc 4.2或更高版本的jdbc驱动程序。不需要线,不需要线 java.sql.* 班级。
从哪里获得java.time类?
JavaSE8、JavaSE9、JavaSE10、JavaSE11及更高版本—标准JavaAPI的一部分,带有捆绑实现。
Java9添加了一些次要的特性和修复。
java se 6和java se 7
大部分java.time功能都是通过三个十个后端口后端口移植到Java6和Java7的。
安卓
android包java.time类的更高版本实现。
对于早期的android(<26),threetenabp项目采用了threeten backport(如上所述)。了解如何使用threetenabp…。
threeten额外的项目用额外的类扩展了java.time。这个项目是java.time将来可能添加的一个试验场。您可以在这里找到一些有用的类,例如 Interval , YearWeek , YearQuarter ,等等。

jmp7cifd

jmp7cifd3#

方法: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());
}

方法:2

LocalDate 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 对象并从其对象中检索年份值。

相关问题