如何将“2012-03-04 00:00:00.0”转换为日期格式为“dd-mm-yyyy HH:mm:ss”使用Java

时间:2012-03-04 09:54:44

标签: java jdbc

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

  

java.text.ParseException:无法解析的日期:“2012-03-04 00:00:00.0”           at java.text.DateFormat.parse(Unknown Source)           at 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)           at 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)           at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)           在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)           at 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(未知来源)

请帮我弄清楚这是怎么回事。以及如何将其转换为正确的格式。

我得到异常的代码片段如下: -

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();

}

8 个答案:

答案 0 :(得分:17)

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

我的印象是你试图通过重复使用相同的格式进行解析和输出来快捷方式? 使用两种格式,然后!

// 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);

答案 1 :(得分:3)

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

    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);

答案 2 :(得分:1)

TL;博士

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

java.time

其他Answers使用现在遗留的麻烦的旧日期时间类,完全由现代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

     

ldtTruncated:2012-03-04T00:00

     

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

关于java.time

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

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

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

从哪里获取java.time类?

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

检查此代码.. 您可以使用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();
            }

答案 5 :(得分:0)

我认为这是您正在寻找的代码:

    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));

答案 6 :(得分:0)

您可以使用此课程:

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;
    }
}

答案 7 :(得分:0)

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;
      }