我是Android新手并尝试通过制作小代码来练习。 我试图在日期上有所不同,并根据它显示文本视图。 但是我在Android手机上当天得到了不同的区别。 比如当我打开应用程序时,它表示天数差异为5。 我关闭它,重新打开它,现在它说diff是4!
在模拟器上它工作正常。 我正在使用以下代码。 任何人都可以提出一些改进建议吗?
package com.practice.tablet;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class TabletsSchedule extends Activity {
public TextView tvToday;
public TextView tvMedStartDate;
public TextView tvMessage;
public TextView tvDiffInDays;
public static final String LOGGER = "ADITYA";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvToday=(TextView)findViewById(R.id.TextView01);
tvMedStartDate=(TextView)findViewById(R.id.TextView001);
tvMessage=(TextView)findViewById(R.id.TextView05);
tvDiffInDays=(TextView)findViewById(R.id.TextView06);
String[] months = {"January", "February",
"March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
Calendar today = Calendar.getInstance();
int day= today.get(Calendar.DAY_OF_MONTH);
int month=today.get(Calendar.MONTH);
int year=today.get(Calendar.YEAR);
String strMonth = months[month];
Log.d(LOGGER, "displaying today");
tvToday.setText("Today is "+day+" "+strMonth+" "+year);
Calendar medStartDate = Calendar.getInstance();
//DOB.set(year, monthOfYear+1, dayOfMonth);
medStartDate.set(Calendar.DAY_OF_MONTH, 27);
medStartDate.set(Calendar.MONTH,10);
medStartDate.set(Calendar.YEAR,2011);
int day1= medStartDate.get(Calendar.DAY_OF_MONTH);
int month1=medStartDate.get(Calendar.MONTH);
int year1=medStartDate.get(Calendar.YEAR);
String strMonth1 = months[month1];
//String med = medStartDate.toString().toString();
tvMedStartDate.setText("Medicine Start Date is "+day1+" "+strMonth1+" "+year1);
long diff = today.getTimeInMillis() - medStartDate.getTimeInMillis();
long days = diff / (24 * 60 * 60 * 1000);
tvDiffInDays.setText("Difference in days is "+days);
Log.d(LOGGER, "days is "+days);
if (days%2!=0){
tvMessage.setText("Today you have to take two tablets");
}
if (days%2==0){
tvMessage.setText("Today you have to take one tablet");
}
}
}
答案 0 :(得分:1)
使用此:
...
Calendar medStartDate = Calendar.getInstance();
medStartDate.clear();
medStartDate.set(Calendar.DAY_OF_MONTH, 27);
medStartDate.set(Calendar.MONTH,10);
medStartDate.set(Calendar.YEAR,2011);
...
此外,您应该在某处(Ex.day,month,year等)存储today
对象的重要值,同样也应该清除它。之后,你可以把这些值放回去,最后你可以用它来与medStartDate
进行比较。它会避免因为时间差异而得到的问题。