Android / Java - 日期差异 [英] Android/Java - Date Difference in days

查看:103
本文介绍了Android / Java - 日期差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am getting the current date (in format 12/31/1999 i.e. mm/dd/yyyy) as using the below code:

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

我的格式如下:2010-08-25(即yyyy / mm / dd),

and I am having another date in format as: 2010-08-25 (i.e. yyyy/mm/dd) ,

所以我想查找几天之间的日期之间的差异,我如何在几天内找到差异?

so I want to find the difference between date in number of days, how do I find difference in days?

(换句话说,我想查找 CURRENT DATE - yyyy / mm / dd格式化日期之间的差异

(In other words, I want to find the difference between CURRENT DATE - yyyy/mm/dd formatted date)

推荐答案

不是一个可靠的方法,更好地使用 JodaTime

Not really a reliable method, better of using 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

这是一个近似...

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

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

To Parse the date from a string, you could use

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

虽然,因为你确定日期格式...
你也可以在它的Substrings上做 Integer.parseInt()来获取它们的数值。

Although, since you're sure of the date format... You Could also do Integer.parseInt() on it's Substrings to obtain their numeric values.

这篇关于Android / Java - 日期差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆