[英]How to set date and time in a specific format
使用此代碼后,我得到一個java.lang.IllegalArgumentException: DTSTART cannot be empty
。 該錯誤來自:
碼:
Calendar calender = Calendar.getInstance();
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
String eventTime="12:00:AM 11:59:PM";
String[] time=eventTime.split(" ");
String[] execttime=time[0].split(":");
String eventStartDate="06 Feb 2014"+" " + execttime[0]+":"+execttime[1]+":00";
long startDate=getDateCurrentMillis(eventStartDate);
values.put(CalendarContract.Events.DTSTART,
startDate);
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(EventDetail.this)+ "events");
public static long getDateCurrentMillis(String startDate) {
SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.getDefault());
sfd.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date d = sfd.parse(startDate);
return d.getTime();
} catch (Exception e) {
System.out.println("");
}
return 0;
}
嘗試這個:
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, h:mm a");
String date = df.format(Calendar.getInstance().getTime());
該問題正在您的getDateCurrentMillis
方法中發生。 是否由於SimpleDateFormat
指定的格式錯誤而無法分析日期,從而導致始終返回0。 在DTSTART中傳遞0會使您的應用崩潰。
看來您的eventStartDate是這樣的格式
String date = "06 Feb 2014 12:00:00";
因此,以這種方式制作您的SimpleDateFormat對象
SimpleDateFormat sfd = new SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.getDefault());
讓我知道我是否正確地觀察了您的日期格式,如果在通過之前未打印日期並在您的SimpleDateFormat
對象中進行相應更改或在評論中發表,則將進行必要的更改。
//to pick date
DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
}
//to pick time
TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
myCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
myCalendar.set(Calendar.MINUTE, minute);
updateLabel();
}
};
有關更多信息,請使用此鏈接
http://www.java-samples.com/showtutorial.php?tutorialid=1520
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.