让Android查找日期并计算此时间与现在之间的天数

时间:2013-07-02 15:42:36

标签: java android date

我在这方面真的很新。 但我想找出例如2013年7月的第一个星期天然后Android应该计算从现在到现在的日子。 非常感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

 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

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

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

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

  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....

答案 1 :(得分:2)

如果您要对Java中的日期进行一些高级计算,我建议使用Joda库(http://joda-time.sourceforge.net)。

使用此库来解决您的问题,可以这样做:

LocalDate firstSundayOfJuly = new LocalDate(2013, 7, 1);
firstSundayOfJuly = firstSundayOfJuly.dayOfWeek().withMaximumValue();
Interval i = new Interval(LocalDate.now().toDateTimeAtStartOfDay(), 
            firstSundayOfJuly.toDateTimeAtStartOfDay());
System.out.println("days = " + i.toDuration().getStandardDays());