0

谁能告诉如何从“今天”中减去字符串“之后”以获得天差。

import java.text.*;
import java.util.*;


public class Main {
public static void main(String args[]){


SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Calendar cal=Calendar.getInstance();
String today=sdf.format(cal.getTime());
System.out.println(today);
cal.add(Calendar.DATE, 20);
String After=sdf.format(cal.getTime());
System.out.println(After);

}
}
4

4 回答 4

4

使用 java8 会更容易,您不需要减去表示日期的长值并改回天、小时和分钟。

Date today= LocalDate.now();
Date futureDate = LocalDate.now().plusDays(1);
long days = Period.between(today, futureDate).getDays();

Period&LocalDate类在#java8 中可用

LocalDate文档

LocalDate 是一个不可变的日期时间对象,它表示一个日期,通常被视为年-月-日。也可以访问其他日期字段,例如一年中的某一天、一周中的某一天和一年中的一周。例如,值“2007 年 10 月 2 日”可以存储在 LocalDate 中。


如果您不使用 java8,请使用 joda-time 库的org.joda.time.Days实用程序来计算

Days day = Days.daysBetween(startDate, endDate);
int days = d.getDays();
于 2014-11-11T05:54:27.527 回答
3

使用JodaTime,以防您没有 Java 8

String timeValue = "2014/11/11";
DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("yyyy/MM/dd").toFormatter();
LocalDate startDate = LocalDate.parse(timeValue, parseFormat);
LocalDate endDate = startDate.plusDays(20);

System.out.println(startDate + "; " + endDate);

Period p = new Period(startDate, endDate);
System.out.println("Days = " + p.getDays());
System.out.println("Weeks = " + p.getWeeks());
System.out.println("Months = " + p.getMonths());

哪个输出...

2014-11-11; 2014-12-01
Days = 6
Weeks = 2
Months = 0
于 2014-11-11T06:10:26.677 回答
0

尝试这个...

愿它对你有所帮助。

import java.util.Date;
import java.util.GregorianCalendar;

// compute the difference between two dates.

public class DateDiff {
  public static void main(String[] av) {
    /** The date at the end of the last century */
    Date d1 = new GregorianCalendar(2010, 10, 10, 11, 59).getTime();

    /** Today's date */
    Date today = new Date();

    // Get msec from each, and subtract.
    long diff = today.getTime() - d1.getTime();

    System.out.println("The 21st century (up to " + today + ") is "
        + (diff / (1000 * 60 * 60 * 24)) + " days old.");
  }
}
于 2014-11-11T08:33:32.670 回答
-1

这可能会帮助你..

SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
    Calendar cal=Calendar.getInstance();
    String today=sdf.format(cal.getTime());
    System.out.println(today);

    cal.add(Calendar.DATE, 20);
    String After=sdf.format(cal.getTime());
    System.out.println(After);

    Date d1 = null;
    Date d2 = null;

    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

    try {
        d1 = format.parse(today);
        d2 = format.parse(After);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    long diff = d2.getTime() - d1.getTime();

    long diffDays = diff / (24 * 60 * 60 * 1000);

    System.out.println("Difference is "+diffDays+" Days");
于 2014-11-11T05:59:52.707 回答