12

I have a date format that I am getting from the database and is a String type. It has a value stored that is like "2012-03-04 00:00:00.0" but I have declared a SimpleDateFormat as "dd-MMM-yyyy HH:mm:ss" which is needed in my project. Now whenever I am retrieving some data alsong with date from database I get a parse Exception with the log as below.

java.text.ParseException: Unparseable date: "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) at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:892) at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:1) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:586) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:614) at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:883) at 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) at com.tcs.tool.iris.aep.selfProfile.controller.UpdateProgressController.onSubmit(UpdateProgressController.java:48) at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:272) at org.springframework.web.servlet.mvc.AbstractFormController.handleInvalidSubmit(AbstractFormController.java:675) at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:275) at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153) at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Unknown Source)

Please help me to figure out whats wrong with this. And how to convert it into the correct format.

The code snippet where I get the exception is as follows:-

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

}

Jacob
  • 14,463
  • 65
  • 207
  • 320
Shiv Kumar Ganesh
  • 3,799
  • 10
  • 46
  • 85
  • 1
    What format did you use for *parsing*? – Has QUIT--Anony-Mousse Mar 04 '12 at 09:55
  • 1
    Please give us a *lot* more context (and code). Why are you parsing text at all when fetching values from the database? Why aren't you getting the value *as a date*? What's the data type in the database? – Jon Skeet Mar 04 '12 at 09:58
  • @Anony-Mousse I have updated the code snippet. And I only need yyyy-MM-dd HH:mm:ss format. Can the data coming form the DB which is in yyyy-MM-dd HH:mm:ss.S format be converted? – Shiv Kumar Ganesh Mar 04 '12 at 10:00
  • 1
    If the format of the date is yyyy-MM-dd HH:mm:ss, obviously you won't be able to parse it with a DateFormat whose pattern is dd-MMM-yyyy HH:mm:ss. That's like painting a car with black painting to make it white. – JB Nizet Mar 04 '12 at 10:02
  • 1
    You should use **two** formats. See my reply below. One for *parsing*, the second for *output* to your intended format. You want String -> Date-Object -> String – Has QUIT--Anony-Mousse Mar 04 '12 at 10:03

8 Answers8

27

The process of converting date strings is rather straightforward. You define the input format, use it to parse the original string, then define the output format, and use that to convert it back to a string.

I have the impression that you are trying to shortcut this, by reusing the same format for parsing and output? Use two formats, then!

// 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);
Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
3

The year is at first place and you need to parse the millisecond part. I've extended the answer to show a simple dateformat conversion:

    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);
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
2

tl;dr

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

java.time

The other Answers use the troublesome old date-time classes that are now legacy, supplanted entirely by the modern java.time classes. For earlier Android, see the last bullets below.

Parse as a LocalDateTime object as your input lacks any indication of time zone or offset-from-UTC.

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

LocalDateTime ldt = LocalDateTime.parse( input ) ;

If you really do not care about the fractional second, chop it off.

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

Specify your custom format for use in generating a String to represent this value.

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

Dump to console.

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

See this code run live at IdeOne.com.

input: 2012-03-04T00:00:00.0

ldt: 2012-03-04T00:00

ldtTruncated: 2012-03-04T00:00

output: 2012-03-04 00:00:00


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You can use this class:

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;
    }
}
profimedica
  • 2,716
  • 31
  • 41
0

Date format with week day name in 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;
      }
Fakhar
  • 3,946
  • 39
  • 35
  • FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. Much of the java.time  functionality is back-ported to Java 6 & Java 7 in the [ThreeTen-Backport](http://www.threeten.org/threetenbp/) project. Further adapted for older versions of Android in the [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Dec 05 '17 at 22:54
0

Try to use the right format (order, M for month) and add the pattern for milliseconds:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Koraktor
  • 41,357
  • 10
  • 69
  • 99
  • I have updated the code snippet. And I only need yyyy-MM-dd HH:mm:ss format. Can the data coming form the DB which is in yyyy-MM-dd HH:mm:ss.S format be converted? – Shiv Kumar Ganesh Mar 04 '12 at 10:01
  • You can either trim the string to the part before the dot or just parse it with the pattern above and just ignore the milliseconds. – Koraktor Mar 04 '12 at 10:04
0

check this code.. You can convert string format into Date format using 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();
            }
John
  • 8,846
  • 8
  • 50
  • 85
0

I think this is the code you are looking for:

    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));
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135