日期时间解析异常:无法在索引 0 处解析文本'2 11, 11 2021 21:35'



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());
  1. 使用day两次:
String timestamp= (String.valueOf(month)+" "+
String.valueOf(day)+", "+   
// String.valueOf(day)+" "+    // REPEATED, delete!
String.valueOf(year)+" "+
String.valueOf(hour)+":"+
String.valueOf(min));

  1. 使用单个字母进行解析
String pattern = "M d, y H:m";

还注意,3个字母表示文本规则(与少于3个字母的数字规则相反(


  1. 使用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。


  1. 不要转换为字符串以获得Timestamp(假设为java.sql.Timestamp(:
mytimestamp = Timestamp.valueOf(localDateTime);  // no toString here

相关内容

  • 没有找到相关文章

最新更新