Am试图从DatePicker
获取Date
,从TimePicker
获取Time
,并将这两个类的值解析为具有DateTimeFormatter
的单个Java时间戳,但logcat抛出此exception
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
Caused by: java.time.format.DateTimeParseException: Text '2 11, 11 2021 21:35' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1777)
at com.example.medicalnotifier.MainActivity.check(MainActivity.java:238)
at com.example.medicalnotifier.MainActivity.onClick(MainActivity.java:341)
我试图格式化日期的代码是这一个
dpicker=datView.findViewById(R.id.user_date);
year=dpicker.getYear();
month=dpicker.getMonth();
day=dpicker.getDayOfMonth();
int hour=timepicker.getCurrentHour();
int min=timepicker.getCurrentMinute();
String pattern = "MMM dd, yyyy HH:mm";
String timestamp= (String.valueOf(month)+" "+String.valueOf(day)+", "+String.valueOf(day)
+" "+String.valueOf(year)+" "+String.valueOf(hour)+":"+String.valueOf(min));
DateTimeFormatter formatter=DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);
LocalDateTime localDateTime = LocalDateTime.from(formatter.parse(timestamp));
mytimestamp=Timestamp.valueOf(localDateTime.toString());
- 使用
day
两次:
String timestamp= (String.valueOf(month)+" "+
String.valueOf(day)+", "+
// String.valueOf(day)+" "+ // REPEATED, delete!
String.valueOf(year)+" "+
String.valueOf(hour)+":"+
String.valueOf(min));
- 使用单个字母进行解析
String pattern = "M d, y H:m";
还注意,3个字母表示文本规则(与少于3个字母的数字规则相反(
- 使用
LocalDateTime.of(year, month, day, hour, minute)
,忽略前2点:
int year = ... // actual code
int month = // "
int day = ... // "
int hour = ... // "
int min = ... // "
LocalDateTime localDateTime = LocalDateTime.of(year, month, day, hour, min);
3 a(如果你的日期选择器将一年中的月份编号从0到11(有些日期选择器有一个可怕的习惯(,你需要在月份编号上加1,因为LocalDateTime
通常希望月份编号为1到12。
- 不要转换为字符串以获得
Timestamp
(假设为java.sql.Timestamp
(:
mytimestamp = Timestamp.valueOf(localDateTime); // no toString here