这是我使用时间计算事件日期和当前日期之间的间隔的代码。我在这里根据时间计算间隔。我不想要那个。我只想要天数的差异。我的意思是考虑事件日期是否为25-09-2015 当前日期:2015年9月23日然后间隔为2天。我需要这种类型的代码。请帮我查一下代码
String eventDate = btn_Date.getText().toString();
DateFormat date = new SimpleDateFormat("dd-M-yyyy");
Date date1 = date.parse(eventDate);
Date currentDate = new Date();
daysBefore = (int) ((date1.getTime() - currentDate.getTime()) / (1000 * 60 * 60 * 24));
答案 0 :(得分:2)
试试这个。这里我也格式化currentDate。这是跳过的时间,现在您可以获得确切的剩余天数。
String eventDate = btn_Date.getText().toString();
DateFormat date = new SimpleDateFormat("dd-M-yyyy");
try {
Date date1 = date.parse(eventDate);
Date currentDate = new Date();
currentDate = date.parse(date.format(currentDate));
long difference = date1.getTime() - currentDate.getTime();
long diff = TimeUnit.DAYS.convert(difference , TimeUnit.MILLISECONDS);
Log.i("remaining days", diff+ "");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 1 :(得分:0)
拥有两个Date
对象后,您可以制作一个小方法来为您计算。像这样:
public static long findDayDiff(Date date1, Date date2) {
long difference = date2.getTime() - date1.getTime();
return TimeUnit.DAYS.convert(difference , TimeUnit.MILLISECONDS);
}
答案 2 :(得分:0)
试试这个,
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class MyTimeActivity extends Activity
{
private static final String TAG = "MyTimeActivity";
//Activity
private Context mContext;
/**
* Called when the activity is first created
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.mContext = this;
Calendar cal1 = stringToCalendar("2012-03-20");
Calendar cal2 = stringToCalendar("2012-03-26");
String elapsedDaysText = getElapsedDaysText(cal1, cal2);
}
public static Calendar stringToCalendar(String dateString)
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
try
{
date = sdf.parse(dateString);
cal.setTime(date);
}
catch(ParseException e)
{
cal = null;
}
return cal;
}
public String getElapsedDaysText(Calendar c1, Calendar c2)
{
long ms1 = c1.getTimeInMillis();
long ms2 = c2.getTimeInMillis();
long ps = (ms2 - ms1) / 1000;
long elapsedDays = ps / 60 / 60 / 24;
String elapsedDaysText = String.format("%d days ago", elapsedDays);
return elapsedDaysText;
}
}
答案 3 :(得分:0)
请找到这个
long days = 0;
long seconds = 0;
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date date1 = sdf.parse(firstDate);
Date date2 = sdf.parse(nextDate);
long diff = date2.getTime() - date1.getTime();
days = diff / (24 * 60 * 60 * 1000);
seconds = days *24*60*60
}catch(Exception e){
e.printStackTrace();
}