【问题标题】:Error while converting String to datetime in Java 8 [duplicate]在 Java 8 中将字符串转换为日期时间时出错 [重复]
【发布时间】:2016-07-19 06:29:51
【问题描述】:

我正在尝试在 java 8 中将 String 转换为 LocalDateTime 对象。下面是我的代码。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

    public class Test {

        public static void main(String[] args){

            String text = "27/11/2016 11:10 pm";
            LocalDateTime date = LocalDateTime.parse(text, DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm a"));

            System.out.println(date);
        }
    }

下面是我遇到的错误。

Exception in thread "main" java.time.format.DateTimeParseException: Text '27/11/2016 11:10 pm' could not be parsed at index 17

【问题讨论】:

    标签: datetime java-8


    【解决方案1】:

    使用String text = "27/11/2016 11:10 PM";

    必须大写。

    【讨论】:

    • 它有效。但我从引导日期选择器中获取 i/p,它就像 am/pm 一样。
    • 不能在将值发送到 parse 方法之前将其转换为大写吗?你能给我一个真实的例子吗?谢谢
    • @anything 在调用 parse 之前将其转换为大写。
    • @RealSkeptic 或者使用不区分大小写的格式化程序...
    【解决方案2】:

    am/pm 需要大写字母。

    String text = "27/11/2016 11:10 PM";
    LocalDateTime date = LocalDateTime.parse(text, DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm a"));
    

    一个上午到下午的文本下午

    see here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 2016-07-30
      相关资源
      最近更新 更多