0

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

4

2 回答 2

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....
于 2013-07-02T15:45:45.253 回答
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());
于 2013-07-02T17:06:35.553 回答