【问题标题】:How to convert "2012-03-04 00:00:00.0" to Date with Format "dd-mm-yyyy HH:mm:ss" Using Java如何使用 Java 将“2012-03-04 00:00:00.0”转换为格式为“dd-mm-yyyy HH:mm:ss”的日期
【发布时间】:2012-03-22 04:08:59
【问题描述】:

我有一个从数据库中获取的日期格式,它是一个字符串类型。它存储的值类似于“2012-03-04 00:00:00.0”,但我已将 SimpleDateFormat 声明为“dd-MMM-yyyy HH:mm:ss”,这在我的项目中是必需的。现在,每当我从数据库中检索一些带有日期的数据时,我都会得到一个解析异常,日志如下。

java.text.ParseException:无法解析的日期:“2012-03-04 00:00:00.0” 在 java.text.DateFormat.parse(未知来源) 在 com.tcs.tool.iris.aep.selfProfile.dao.AepSelfProfileDaoImpl$1.setValues(AepSelfProfileDaoImpl.java:1188) 在 org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:892) 在 org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:1) 在 org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:586) 在 org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:614) 在 org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:883) 在 com.tcs.tool.iris.aep.selfProfile.dao.AepSelfProfileDaoImpl.insertDataIntoActionItems(AepSelfProfileDaoImpl.java:1174) 在 com.tcs.tool.iris.aep.selfProfile.service.AepSelfProfileServiceImpl.insertDataIntoActionItems(AepSelfProfileServiceImpl.java:214) 在 com.tcs.tool.iris.aep.selfProfile.controller.UpdateProgressController.onSubmit(UpdateProgressController.java:48) 在 org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:272) 在 org.springframework.web.servlet.mvc.AbstractFormController.handleInvalidSubmit(AbstractFormController.java:675) 在 org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:275) 在 org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153) 在 org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48) 在 org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790) 在 org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) 在 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) 在 org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) 在 javax.servlet.http.HttpServlet.service(HttpServlet.java:637) 在 javax.servlet.http.HttpServlet.service(HttpServlet.java:717) 在 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) 在 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 在 org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) 在 org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) 在 org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) 在 org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) 在 org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) 在 org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) 在 org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857) 在 org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) 在 org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) 在 java.lang.Thread.run(Unknown Source)

请帮我弄清楚这有什么问题。以及如何将其转换为正确的格式。

我得到异常的代码sn-p如下:-

SimpleDateFormat sdf = new SimpleDateFormat(
                                "dd-MMM-yyyy HH:mm:ss");
                        Calendar currenttime = Calendar.getInstance();
                        java.util.Date currentdate = currenttime.getTime();
                        String currentDateInsert = sdf.format(currentdate);
                        CommentNActionItem commentAndAction = commentActionItem
                                .get(i);
                        java.util.Date datefromDb = null;
                        try {
                            @SuppressWarnings("unused")
                            Date dateF=sdf.parse(commentAndAction.getCreatedDate());
                            datefromDb = (java.sql.Date)sdf.parseObject(commentAndAction.getCreatedDate());
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();

}

【问题讨论】:

  • 你用什么格式解析
  • 请给我们很多更多上下文(和代码)。为什么在从数据库中获取值时要解析文本?为什么你没有得到作为日期的值?数据库中的数据类型是什么?
  • @Anony-Mousse 我已经更新了代码 sn-p。我只需要 yyyy-MM-dd HH:mm:ss 格式。数据库中yyyy-MM-dd HH:mm:ss.S格式的数据可以转换吗?
  • 如果日期的格式是 yyyy-MM-dd HH:mm:ss,显然你将无法使用模式为 dd-MMM-yyyy HH:mm 的 DateFormat 解析它:ss。这就像用黑漆把汽车涂成白色。
  • 您应该使用两种格式。请看我下面的回复。一个用于解析,第二个用于输出到您想要的格式。你想要字符串 -> 日期对象 -> 字符串

标签: java jdbc


【解决方案1】:

转换日期字符串的过程相当简单。您定义输入格式,使用它来解析原始字符串,然后定义输出格式,并使用它来将其转换回字符串。

我的印象是您试图通过重用相同的格式进行解析和输出来简化此操作? 使用两种格式,然后!

// Convert input string into a date
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date date = inputFormat.parse(inputString);

// Format date into output format
DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String outputString = outputFormat.format(date);

【讨论】:

  • 你能提供一个例子来解释我吗?会很有帮助!
  • 更新了更详细的示例。但你应该自己尝试一下!
  • 请注意,hh 是 12 小时格式 (AM/PM),而 HH 是 24 小时格式。
  • SimpleDateFormat 应该始终被实例化为新的并且永远不要重用,因为它不是线程安全的......
【解决方案2】:

年份是第一位的,您需要解析毫秒部分。我已经扩展了答案以显示一个简单的日期格式转换:

    SimpleDateFormat in = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    SimpleDateFormat out = new SimpleDateFormat("dd-MM-yy HH:mm:ss");

    Date date = in.parse("2012-03-04 11:09:00.123");
    String result = out.format(date);
    System.out.println(result);

【讨论】:

  • 我可以将格式转换为 dd-MM-yyyy HH:mm:ss 吗?如 yyyy-MM-dd HH:mm:ss.SSS 格式的 String 可以转换成上面的吗?
【解决方案3】:

tl;博士

LocalDateTime.parse( 
    "2012-03-04 00:00:00.0".replace( " " , "T" ) 
).format(
    DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" )
)

java.time

其他答案使用现在遗留的麻烦的旧日期时间类,完全被现代 java.time 类所取代。对于早期的 Android,请参阅下面的最后一个项目符号。

解析为 LocalDateTime 对象,因为您的输入缺少任何时区指示或与 UTC 的偏移量。

String input = "2012-03-04 00:00:00.0".replace( " " , "T" ) ; 

LocalDateTime ldt = LocalDateTime.parse( input ) ;

如果你真的不关心小数秒,把它砍掉。

LocalDateTime ldtTruncated = ldt.truncatedTo( ChronoUnit.SECONDS ) ;

指定用于生成表示该值的字符串的自定义格式。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = ldtTruncated.format( f ) ;

转储到控制台。

System.out.println( "input: " + input ) ;
System.out.println( "ldt: " + ldt ) ;
System.out.println( "ldtTruncated: " + ldtTruncated ) ;
System.out.println( "output: " + output ) ;

看到这个code run live at IdeOne.com

输入:2012-03-04T00:00:00.0

ldt: 2012-03-04T00:00

ldt截断:2012-03-04T00:00

输出:2012-03-04 00:00:00


关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

从哪里获得 java.time 类?

【讨论】:

    【解决方案4】:

    尝试使用正确的格式(顺序,M 表示月份)并添加毫秒模式:

    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    

    【讨论】:

    • 我已经更新了sn-p的代码。我只需要 yyyy-MM-dd HH:mm:ss 格式。数据库中yyyy-MM-dd HH:mm:ss.S格式的数据可以转换吗?
    • 您可以将字符串修剪到点之前的部分,也可以使用上面的模式对其进行解析而忽略毫秒。
    【解决方案5】:

    检查此代码.. 您可以使用 SimpleDateFormat 将字符串格式转换为日期格式

    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd hh:mm aa ";
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
    Date date = null;
    try {
    
          String date_time_string="2012-03-01 21:15 am";
    
                    date = dateTimeFormat.parse(date_time_string);
                } catch (java.text.ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    

    【讨论】:

      【解决方案6】:

      我认为这是您要查找的代码:

          String dateString = "2012-03-04 00:00:00.0";
          DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
          DateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
          Date date = inputFormat.parse(dateString);
          System.out.println(outputFormat.format(date));
      

      【讨论】:

        【解决方案7】:

        你可以使用这个类:

        import java.text.SimpleDateFormat;
        import java.util.Calendar;
        import java.util.Date;
        import java.util.GregorianCalendar;
        import java.text.ParseException;
        /**
         * Helper class for handling ISO 8601 strings of the following format:
         * "2008-03-01T13:00:00+01:00". It also supports parsing the "Z" timezone.
         */
        public final class ISO8601 {
            /** Transform Calendar to ISO 8601 string. */
            public static String fromCalendar(final Calendar calendar) {
                Date date = calendar.getTime();
                String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(date);
                return formatted.substring(0, 22) + ":" + formatted.substring(22);
            }
        
            /** Get current date and time formatted as ISO 8601 string. */
            public static String now() {
                return fromCalendar(GregorianCalendar.getInstance());
            }
        
            /** Transform ISO 8601 string to Calendar. */
            public static GregorianCalendar toCalendar(final String iso8601string) throws ParseException {
                GregorianCalendar calendar = (GregorianCalendar) GregorianCalendar.getInstance();
                String s = iso8601string;
                Date date = null;
                try{
                    s=s.replace("Z", "+00:00");
                    try {
                        s = s.substring(0, 26) + s.substring(27);
                    } catch (IndexOutOfBoundsException e) {}
                    date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(s);
                }catch(Exception tc)
                {
                    s=s.replace("Z", "+00:00");
                    try {
                        s = s.substring(0, 22) + s.substring(23);
                    } catch (IndexOutOfBoundsException e) {}
                    date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
                }
                calendar.setTime(date);
                return calendar;
            }
        }
        

        【讨论】:

          【解决方案8】:

          Java Android 中带有工作日名称的日期格式

          Input: 2017-08-02T12:54:54+04:00 
          you are required to show results like:
          Output:    Wednesday
                     August 2, 2017 12:54 pm
          
          
          
           public static String getDateFormat(String date){
                String input_date= date;
               //incase you are getting format 2017-08-02T12:54:54+04:00 you need to
              // replace T with " " doing so String input_date = date.replace("T","");
                SimpleDateFormat format1=new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date dt1= null;
                try {
                  dt1 = format1.parse(input_date);
                } catch (ParseException e) {
                  e.printStackTrace();
                }
          
                DateFormat format2=new SimpleDateFormat("EEEE");
                String finalDay=format2.format(dt1);
                String stringDate = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.SHORT).format(dt1); // for seconds removal use DateFormat.SHORT in second parameter  
                return finalDay+"\n"+stringDate;
                }
          

          【讨论】:

          • 仅供参考,java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等麻烦的旧日期时间类现在已被 java.time 类所取代。 ThreeTen-Backport 项目中的大部分 java.time 功能都向后移植到 Java 6 和 Java 7。在 ThreeTenABP 项目中进一步适用于旧版本的 Android。见How to use ThreeTenABP…
          猜你喜欢
          • 1970-01-01
          • 2016-01-14
          • 1970-01-01
          • 2020-08-28
          • 1970-01-01
          • 2019-08-25
          • 2015-02-03
          • 1970-01-01
          • 2019-07-19
          相关资源
          最近更新 更多