android获取当前日期是第几天,Android:如何计算几天前的日期?

4 个答案:

答案 0 :(得分:11)

更好的方法是使用add方法而不是set:

cal.add(DAY_OF_YEAR, -2);

即。确保它也适用于月份的第一天等。

答案 1 :(得分:2)

我使用以下功能:

public static Date getStartOfDay() {

Calendar calendar = Calendar.getInstance();

calendar.setTime(new Date());

calendar.set(Calendar.HOUR_OF_DAY, 0);

calendar.set(Calendar.MINUTE, 0);

calendar.set(Calendar.SECOND, 0);

calendar.set(Calendar.MILLISECOND, 0);

return calendar.getTime();

}

public static long getDaysAgo(Date date){

final long diff = getStartOfDay().getTime() - date.getTime();

if(diff < 0){

// if the input date millisecond > today's 12:00am millisecond it is today

// (this won't work if you input tomorrow)

return 0;

}else{

return TimeUnit.MILLISECONDS.toDays(diff)+1;

}

}

答案 2 :(得分:2)

您可以执行以下操作:

Calendar cal=Calendar.getInstance();

int currentDay=cal.get(Calendar.DAY_OF_MONTH);

//Set the date to 2 days ago

cal.set(Calendar.DAY_OF_MONTH, currentDay-2);

然后你可以得到日期:

cal.getTime(); //The date 2 days ago

答案 3 :(得分:1)

相同类型的代码,但使用Joda-Time 2.3库和Java 7。

DateTime dateTime = new DateTime( 2014, 2, 3, 7, 8, 9 );

DateTime twoDaysPrior = dateTime.minusDays( 2 );

dateTime: 2014-02-03T07:08:09.000-08:00

twoDaysPrior: 2014-02-01T07:08:09.000-08:00

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值