1

I'm having a String having date in it, I need hh:mm:ss to be added to the date, but when i use dateFormat it gives me ParseException. Here is the code:

DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String startDate = "2013-09-25";
Date frmDate;
frmDate = sdff.parse(startDate);

System.out.println("from date = " + frmDate);

I get parse exception for the abv code. But if i remove the hh:mm:ss from the Date format it works fine and the output will be from date = Wed Sep 25 00:00:00 IST 2013. But I need output like from date = 2013-09-25 00:00:00

Please help me. Thanks in advance.

madhu
  • 1,010
  • 5
  • 20
  • 38
  • 1
    Refer http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html for date formats – Jitender Dev Sep 25 '13 at 05:27
  • 1
    look for this [LINK](http://stackoverflow.com/questions/4772425/format-date-in-java) – Husam Sep 25 '13 at 05:42
  • 2
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Mar 27 '18 at 20:32

6 Answers6

8

You'll need 2 SimpleDateFormat objects for that. One to parse your current date string and the other to format that parsed date to your desired format.

// This is to parse your current date string
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDate = "2013-09-25";
Date frmDate = sdf.parse(startDate); // Handle the ParseException here

// This is to format the your current date to the desired format
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String frmDateStr = sdff.format(frmDate);

Edit:-

Date doesn't have a format as such. You can only get a String representation of it using the SDF. Here an excerpt from the docs

A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.

And regarding your problem to insert it in the DB, java Date can be as such persisted in the DB date format. You don't need to do any formatting. Only while fetching the date back from DB, you can use the to_char() method to format it.

Rahul
  • 44,383
  • 11
  • 84
  • 103
  • @ R.J: Your code works fine but I need to store in db as a type Date, so now String frmDateStr is having the format I want, but again if i parse it to Date it gives me Sat Sep 14 00:00:00 IST 2013, which i'm facing problem. I need final data to be of the type Date. – madhu Sep 25 '13 at 05:37
1

parse() is used to convert String to Date.It requires the formats to be matched otherwise you will get exception.
format() is used convert the date into date/time string.
Accroding to your requirement you need to use above two methods.

    DateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    String startDate = "2013-09-25";
    Date parsedDate = parser.parse(startDate);
    String formattedDate = dateFormatter.format(parsedDate);//this will give your expected output
Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
  • @ Prabhakar: Your code works fine but I need to store in db as a type Date, so now String frmDateStr is having the format I want, but again if i parse it to Date it gives me Sat Sep 14 00:00:00 IST 2013, which i'm facing problem. I need final data to be of the type Date. – madhu Sep 25 '13 at 05:40
1

tl;dr

LocalDate.parse( "2013-09-25" )       // Parse the string as a date-only object lacking time-of-day and lacking time zone.
.atStartOfDay(                        // Let java.time determine the first moment of the day. Not always 00:00:00 because of anomalies such as Daylight Saving Time (DST). 
    ZoneId.of( "America/Montreal" )   // Specify a time zone using legitimate `continent/region` name rather than 3-4 letter pseudo-zones.
)                                     // Returns a `ZonedDateTime` object.
.toString()                           // Generate a string in standard ISO 8601 format, wisely extended from the standard by appending the name of the time zone in square brackets.

2013-09-25T00:00-04:00[America/Montreal]

To generate your string, pass a DateTimeFormatter.

LocalDate.parse( "2013-09-25" )            // Parse the string as a date-only object lacking time-of-day and lacking time zone.
.atStartOfDay(                             // Let java.time determine the first moment of the day. Not always 00:00:00 because of anomalies such as Daylight Saving Time (DST). 
    ZoneId.of( "America/Montreal" )        // Specify a time zone using legitimate `continent/region` name rather than 3-4 letter pseudo-zones.
)                                          // Returns a `ZonedDateTime` object.
.format(                                   // Generate a string representing the value of this `ZonedDateTime` object.
    DateTimeFormatter.ISO_LOCAL_DATE_TIME  // Formatter that omits zone/offset.
).replace( "T" , " " )                     // Replace the standard’s required 'T' in the middle with your desired SPACE character.

2013-09-25 00:00:00

Details

Your formatting pattern must match your input, as pointed out by others. One formatter is needed for parsing strings, another for generating strings.

Also, you are using outmoded classes.

java.time

The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

You can parse a string to produce a LocalDate. The standard ISO 8601 formats are used in java.time by default. So no need to specify a formatting pattern.

LocalDate ld = LocalDate.parse( "2013-09-25" ) ;

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 2013 , 9 , 25 ) ;  // Years use sane direct numbering (2013 means year 2013). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.

LocalDate ld = LocalDate.of( 2013 , Month.SEPTEMBER , 25 ) ;

Formats

If you want to get the first moment of the day for that date, apply a time zone. As mentioned above, a date and time-of-day require the context of a time zone or offset-from-UTC to represent a specific moment on the timeline.

Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00. Let java.time determine the first moment of the day.

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ld.atZone( z ) ;

If you want output in the format shown in your Question, you can define your own format. I caution you against omitting the time zone or offset info from the resulting string unless you are absolutely certain the user can discern its meaning from the greater context.

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

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.

With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

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

It is because your string is yyyy-MM-dd, but the date format u defined is yyyy-MM-dd hh:mm:ss. If you change your string startDate to yyyy-MM-dd hh:mm:ss it should work

Crickcoder
  • 2,135
  • 4
  • 22
  • 36
0
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.parse(sdf.format(new Date()));

This will return a Date type

ThilinaMD
  • 365
  • 3
  • 13
0

The issue is '2013-09-25' date cannot be parsed to 'yyyy-MM-dd hh:mm:ss' date format. First you need to parse following date into its matching pattern which is 'yyyy-MM-dd'.

Once it is parsed to its correct pattern you can provide the date pattern you prefer which is 'yyyy-MM-dd hh:mm:ss'.

Now you can format the Date and it will output the date as you preferred.

SimpleDateFormat can be used to achieve this outcome.

Try this code.

    String startDate = "2013-09-25";
    DateFormat existingPattern = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat newPattern = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    Date date = existingPattern.parse(startDate);
    String formattedDate = newPattern.format(date);
    System.out.println(formattedDate); //outputs: 2013-09-25 00:00:00
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
  • Thanks for wanting to contribute. However, in 2018 please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jul 25 '18 at 09:13