gpt4 book ai didi

java - 在 android 中设置时日期不正确

转载 作者:行者123 更新时间:2023-11-30 04:19:07 25 4
gpt4 key购买 nike

我正在使用以下代码。当我按下 editText 时,它会显示一个日历并设置日期。

          private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {

public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};

private void updateDisplay()
{
int cmpYear ;
int cmpMonth ;
int cmpDay;

final Calendar c = Calendar.getInstance();
cmpYear = c.get(Calendar.YEAR);
cmpMonth = c.get(Calendar.MONTH);
cmpDay = c.get(Calendar.DAY_OF_MONTH);

if (cmpMonth == mMonth && cmpYear == mYear && cmpDay == mDay)
date.setText("Today");
else if (cmpMonth == mMonth && cmpYear == mYear && cmpDay == (mDay - 1))
date.setText("Yesterday");
else
{
date.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mDay).append("-")
.append(mMonth + 1).append("-")
.append(mYear).append(" "));
}

java.util.Date today = new java.util.Date();
long t = today.getTime();
java.sql.Date dt = new java.sql.Date(t);

dt.setYear(mYear);
dt.setMonth(mMonth);
dt.setDate(mDay);

transaction.transactionDateTime = dt;
}

//这里是问题所在,mYear、mMonth、mDay 显示正确的值 1,3,2012 但是当我在 dt 中设置它们时,dt 将 mYear 保存为 3079 而不是 2012。请告诉我如何解决这个日期问题

最好的问候

最佳答案

我很惊讶它给你的是 3079 而不是 3912,这是我预期的 Date.setYear记录在案:

Sets the year of this Date object to be the specified value plus 1900. This Date object is modified so that it represents a point in time within the specified year, with the month, date, hour, minute, and second the same as before, as interpreted in the local time zone. (Of course, if the date was February 29, for example, and the year is set to a non-leap year, then the new date will be treated as if it were on March 1.)

请注意,这是一个已弃用的方法 - 您真的不应该使用它。

使用 Calendar 进行日历计算,然后通过调用 calendar.getTime() 及时找到合适的时刻。您可以从中构造一个 java.sql.Date

(理想情况下,您应该改用 Joda Time,但在 Android 应用中这对您来说可能过于依赖。)

关于java - 在 android 中设置时日期不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9528963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com