我该如何在Android中2日期间减去?

问题描述 投票:-1回答:3

我从当前系统时间拿起从日期选取器和其他日期。当我想减去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 /日从当前时间减去日期我得到这样的结果:

-1879 1 3 10 24 34

什么一年不正确。

java android date calendar
3个回答
1
投票
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();

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


1
投票

制法: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对象添加差值和检索,从物体年份。

0
投票

tl;dr

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

看到这个code run live at IdeOne.com

1998-10-31

Avoid legacy date-time classes

切勿使用CalendarDate类。那些可怕的班级是由java.time类取代年前。

LocalDate

LocalDate类表示没有时间的天,没有time zoneoffset-from-UTC日期,唯一的价值。

时区是在确定的日期是至关重要的。对于任何给定的时刻,日期由区全球各地的变化。例如,午夜Paris France几分钟后是新的一天,同时还“昨天”在Montréal Québec

如果没有指定时区,JVM的隐式应用当前默认时区。该默认可以在运行时(!)期间change at any moment,因此您的结果可能会有所不同。最好明确指定所需/预期的时区作为参数。

proper time zone name的格式指定一个Continent/Region,如America/MontrealAfrica/Casablanca,或Pacific/Auckland。切勿使用2-4个字母的缩写,如ESTIST,因为它们不是真正的时区,不规范,甚至不是唯一的(!)。

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一月至十二月。

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对象,使你的代码更自我记录,确保有效的值,并提供type-safety。同上,用于YearYearMonth

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Period

为了表示年 - 月 - 日术语翼展的时间,使用Period

Period p = Period.ofDays( 5 ) ;

Date-time math

您可以通过调用plus…minus…方法java.time执行日期时间值的加减。

LocalDate later = ldt.plus( p ) ;

Duration

如果你想代表天(时间24小时块,无关日历),小时,分钟,秒和分数第二方面翼展的时间,使用Duration

Year

你的问题不太清楚,但似乎是对2000年有什么特别之处当年与java.time类。

您可以询问java.time类的年份。

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

About java.time

java.time框架是建立在Java 8和更高版本。这些类取代的麻烦老legacy日期时间类,如java.util.DateCalendar,与SimpleDateFormat

该项目Joda-Time,现在在maintenance mode,建议迁移到java.time类。

要了解更多信息,请参见Oracle Tutorial。和搜索堆栈溢出了很多例子和解释。规格是JSR 310

您可以直接与数据库交换java.time对象。使用符合JDBC driver或更高版本的JDBC 4.2。无需串,没有必要java.sql.*类。

从哪里获取java.time类?

该项目ThreeTen-Extra与java.time其他类延伸。该项目是为将来可能增加的java.time试验场。您可以在这里找到一些有用的类,如IntervalYearWeekYearQuartermore

© www.soinside.com 2019 - 2024. All rights reserved.