Android/Java - 日期差异

Par*_*ani 77 java android date

我使用以下代码获取当前日期(格式为12/31/1999,即mm/dd/yyyy):

Textview txtViewData;
txtViewDate.setText("Today is " +
        android.text.format.DateFormat.getDateFormat(this).format(new Date()));
Run Code Online (Sandbox Code Playgroud)

我的格式为另一个日期:2010-08-25(即yyyy/mm/dd),

所以我想找出日期的天数之间的差异,我如何找到天数的差异?

(换句话说,我想找出CURRENT DATE - yyyy/mm/dd格式化日期之间的区别)

st0*_*0le 124

不是真正可靠的方法,更好地使用JodaTime

  Calendar thatDay = Calendar.getInstance();
  thatDay.set(Calendar.DAY_OF_MONTH,25);
  thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
  thatDay.set(Calendar.YEAR, 1985);

  Calendar today = Calendar.getInstance();

  long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
Run Code Online (Sandbox Code Playgroud)

这是一个近似值......

long days = diff / (24 * 60 * 60 * 1000);
Run Code Online (Sandbox Code Playgroud)

要从字符串中解析日期,您可以使用

  String strThatDay = "1985/08/25";
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
  Date d = null;
  try {
   d = formatter.parse(strThatDay);//catch exception
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 


  Calendar thatDay = Calendar.getInstance();
  thatDay.setTime(d); //rest is the same....
Run Code Online (Sandbox Code Playgroud)

虽然,因为你确定日期格式...你也可以Integer.parseInt()在它的子字符串上获取它们的数值.

  • 这对DST更改无法可靠地工作. (4认同)
  • 有时这段代码会因为在划分毫秒时出现舍入问题(缺少它)而休息一天.这对我有用:`Math.round(millisBetweenDates*1f/TimeUnit.MILLISECONDS.convert(1,TimeUnit.DAYS));` (3认同)

Sam*_*uel 80

这不是我的工作,在这里找到答案.不希望将来有破损的链接:).

关键是这条线用于考虑日光设置,参考完整代码.

TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Run Code Online (Sandbox Code Playgroud)

或尝试通过TimeZone 作为参数daysBetween(),并呼吁setTimeZone()sDateeDate对象.

所以这里:

public static Calendar getDatePart(Date date){
    Calendar cal = Calendar.getInstance();       // get calendar instance
    cal.setTime(date);      
    cal.set(Calendar.HOUR_OF_DAY, 0);            // set hour to midnight
    cal.set(Calendar.MINUTE, 0);                 // set minute in hour
    cal.set(Calendar.SECOND, 0);                 // set second in minute
    cal.set(Calendar.MILLISECOND, 0);            // set millisecond in second

    return cal;                                  // return the date part
}
Run Code Online (Sandbox Code Playgroud)

getDatePart()取自此处

/**
 * This method also assumes endDate >= startDate
**/
public static long daysBetween(Date startDate, Date endDate) {
  Calendar sDate = getDatePart(startDate);
  Calendar eDate = getDatePart(endDate);

  long daysBetween = 0;
  while (sDate.before(eDate)) {
      sDate.add(Calendar.DAY_OF_MONTH, 1);
      daysBetween++;
  }
  return daysBetween;
}
Run Code Online (Sandbox Code Playgroud)

细微差别:找到两个日期之间的差异并不像减去两个日期并将结果除以(24*60*60*1000)那样简单.事实上,它的错误!

例如: 2007年3月24日和2007年3月25日这两个日期之间的差异应为1天; 但是,使用上述方法,在英国,你将获得0天!

亲眼看看(下面的代码).以毫秒为单位将导致四舍五入的错误,一旦你有一些像Daylight Savings Time这样的小东西进入画面,它们就会变得非常明显.

完整代码:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateTest {

public class DateTest {

static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");

public static void main(String[] args) {

  TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));

  //diff between these 2 dates should be 1
  Date d1 = new Date("01/01/2007 12:00:00");
  Date d2 = new Date("01/02/2007 12:00:00");

  //diff between these 2 dates should be 1
  Date d3 = new Date("03/24/2007 12:00:00");
  Date d4 = new Date("03/25/2007 12:00:00");

  Calendar cal1 = Calendar.getInstance();cal1.setTime(d1);
  Calendar cal2 = Calendar.getInstance();cal2.setTime(d2);
  Calendar cal3 = Calendar.getInstance();cal3.setTime(d3);
  Calendar cal4 = Calendar.getInstance();cal4.setTime(d4);

  printOutput("Manual   ", d1, d2, calculateDays(d1, d2));
  printOutput("Calendar ", d1, d2, daysBetween(cal1, cal2));
  System.out.println("---");
  printOutput("Manual   ", d3, d4, calculateDays(d3, d4));
  printOutput("Calendar ", d3, d4, daysBetween(cal3, cal4));
}


private static void printOutput(String type, Date d1, Date d2, long result) {
  System.out.println(type+ "- Days between: " + sdf.format(d1)
                    + " and " + sdf.format(d2) + " is: " + result);
}

/** Manual Method - YIELDS INCORRECT RESULTS - DO NOT USE**/
/* This method is used to find the no of days between the given dates */
public static long calculateDays(Date dateEarly, Date dateLater) {
  return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
}

/** Using Calendar - THE CORRECT WAY**/
public static long daysBetween(Date startDate, Date endDate) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

手册 - 2007年1月1日至2007年1月2日之间的天数为:1

日历 - 日期:2007年1月1日至2007年1月2日:1


手册 - 2007年3月24日至2007年3月25日之间的天数为:0

日历 - 日期:2007年3月24日至2007年3月25日:1


Lis*_*nne 37

大多数答案都很好,适合你的问题

所以我想找出日期的天数之间的差异,我如何找到天数的差异?

我建议这种非常简单明了的方法可以保证在任何时区给你正确的差异:

int difference= 
((int)((startDate.getTime()/(24*60*60*1000))
-(int)(endDate.getTime()/(24*60*60*1000))));
Run Code Online (Sandbox Code Playgroud)

就是这样!


Jer*_*erg 24

使用jodatime API

Days.daysBetween(start.toDateMidnight() , end.toDateMidnight() ).getDays() 
Run Code Online (Sandbox Code Playgroud)

'start'和'end'是你的DateTime对象.要将日期字符串解析为DateTime对象,请使用parseDateTime方法

还有一个特定于Android的JodaTime库.

  • thanx用于支持,但如果使用Android/JAVA代码完成,则不乐意使用其他API (3认同)
  • Joda为+1.Java Calendar API是一个糟糕的混乱,Joda干净漂亮. (2认同)

mar*_*hiz 14

这个片段占夏令时,是O(1).

private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;

private static long getDateToLong(Date date) {
    return Date.UTC(date.getYear(), date.getMonth(), date.getDate(), 0, 0, 0);
}

public static int getSignedDiffInDays(Date beginDate, Date endDate) {
    long beginMS = getDateToLong(beginDate);
    long endMS = getDateToLong(endDate);
    long diff = (endMS - beginMS) / (MILLISECS_PER_DAY);
    return (int)diff;
}

public static int getUnsignedDiffInDays(Date beginDate, Date endDate) {
    return Math.abs(getSignedDiffInDays(beginDate, endDate));
}
Run Code Online (Sandbox Code Playgroud)


Ris*_*tam 6

这对我来说是简单而且最好的计算,可能适合您.

       try {
            /// String CurrDate=  "10/6/2013";
            /// String PrvvDate=  "10/7/2013";
            Date date1 = null;
            Date date2 = null;
            SimpleDateFormat df = new SimpleDateFormat("M/dd/yyyy");
            date1 = df.parse(CurrDate);
            date2 = df.parse(PrvvDate);
            long diff = Math.abs(date1.getTime() - date2.getTime());
            long diffDays = diff / (24 * 60 * 60 * 1000);


            System.out.println(diffDays);

        } catch (Exception e1) {
            System.out.println("exception " + e1);
        }
Run Code Online (Sandbox Code Playgroud)