繁体   English   中英

java.text.ParseException:无法解析的日期异常

[英]java.text.ParseException: Unparseable date exception

如果我对Date对象执行toString ,则得到以下输出

2016-04-13 22:00:01.0

我正在执行以下操作以再次将对象转换为数据

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:HH:mm:SS");
Date convertedDate = (Date) formatter.parse(timestamp.toString());

但是得到ParseException

我正在尝试将输出作为日期对象如下2016-04-13 22:00:01

该测试应涵盖您的示例:

首先从评论:

    SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss zzz yyyy");
    Date convertedDate = formatter.parse("Thu Apr 14 15:24:14 CEST 2016")
    System.out.print(convertedDate);

问题第二:

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    Date convertedDate = formatter.parse("2016-04-13 22:00:01.0");
    System.out.print(convertedDate);

这完全取决于您要接收的输入String。

您不应使用Date :: toString方法,而应使用格式化程序,因为区域和格式都不会有问题。 最好完全控制数据流。

现在,如果要将其转换为“ 2016-04-13 22:00:01”格式,只需使用:

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String formatedDate = formatter.format(convertedDate);

从具有特定日期格式的String解析为Date对象:

    String dateString = "2016-04-13 22:00:01.0";
SimpleDateFormat formatterFullMilliseconds = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS" );

Date dateFromDateString = formatterFullMilliseconds.parse( dateString );

System.out.println( dateFromDateString ); // Output: Wed Apr 13 22:00:01 CEST 2016

将java.util.Date对象解析为所需的字符串表示形式:

SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
System.out.println( formatter.format( dateFromDateString ) ); // 2016-04-13 22:00:01
System.out.println( formatter.format( new Date() ) ); // 2016-04-14 15:29:04

这正是您要执行的操作,以逃脱java.text.ParseException:无法解析的日期异常

Date date = new Date();

SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = sp.parse(sp.format(date));
System.out.println(dt.toString());
yyyy-MM-dd:HH:mm:SS

应该

yyyy-MM-dd HH:mm:ss.S

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM