我想在我的Android应用程序中单独处理日期和时间,单独说我的意思是设置时间而不影响日期,反之亦然,所以,当设置时间时:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR + 1990, Calendar.MONTH, Calendar.DAY_OF_MONTH, hours, minutes, 0);
它完美无缺,但只设置日期:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new_date);
我遇到了将时间设置为 00:00:00 的问题,因此,我尝试先保存时间值并按以下方式设置日期:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new_date);
calendar.set(Calendar.YEAR + 1990, Calendar.MONTH, Calendar.DAY_OF_MONTH, saved_hours, saved_minutes, 0);
但是这会将日期保存为默认值,因为(Calendar.YEAR
|| .MONTH
|| .DAY_OF_MONTH
)会返回零日期设备的值是1990年的日期,尽管我在设置新的日期后没有激活此命令。
提示:不推荐使用方法(mDate.getYear()
,mDate.getMonth
,.....等)。
答案 0 :(得分:0)
要分别设置日期和时间,您可以使用此代码
Calendar cal = Calendar.getInstance();
// Note: Months value is MonthNumber-1 (Jan is 0, Feb is 1 and so on).
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DATE, 24);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.HOUR,1); // when wanting to set it as 12 Hour system
cal.set(Calendar.HOUR_OF_DAY,13); // when wanting to set it as 24 Hour system
cal.set(Calendar.MINUTE,45);
cal.set(Calendar.SECOND,52);
// set the year,month and day to something else
//set(int year,int month,int day)
cal.set(1995, 5, 25);
// set(int year,int month,int day,int hourOfDay, int minute,int second)
cal.set(1995, 5, 25, 04, 15, 20);