Kuntal Basu
Kuntal Basu

Reputation: 830

How to format a date String into desirable Date format

I was trying to format a string into date.

For this I have written a code:-

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(sdf.format( cal.getTime() ));

This is fine.. But now I want to convert a string into a date formatted like above.. For example

String dt="2010-10-22";

And the output should be like this:- 2010-10-22T00:00:00

How do I do this?

Upvotes: 2

Views: 1516

Answers (5)

ThmHarsh
ThmHarsh

Reputation: 601

Date Format Example

Containing the Conversion of String Date object from one format to another

Upvotes: 0

puug
puug

Reputation: 941

If your input is going to be ISO, you could also look at using the Joda Time API, like so:

LocalDateTime localDateTime = new LocalDateTime("2010-10-22");
System.out.println("Formatted time: " + localDateTime.toString());

Upvotes: 1

gavinb
gavinb

Reputation: 20018

The same class you use for output formatting of dates can also be used to parse dates on input.

To use your example, to parse the sample date:

String dt = "2010-10-22";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormatter.parse(dt));

The fields that are not specified (ie. hour, minutes, etc) will be 0. So your same code can be used to format the date on output.

Upvotes: 0

JonVD
JonVD

Reputation: 4268

This should do it for you, remember to wrap it in a try-catch block just in case.

DateFormat dt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 
try
{
Date today = dt.parse("2010-10-22T00:00:00");                       
System.out.println("Your Date = " + dt.format(today));       
} catch (ParseException e)    
{
//This parse operation may not be successful, in which case you should handle the ParseException that gets thrown.
//Black Magic Goes Here
} 

Upvotes: 2

David Barr
David Barr

Reputation: 189

String dt = "2010-10-22";

SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition ps = new ParsePosition(0)
Date date = sdfIn.parse(dt, pos)

SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

System.out.println(sdfOut.format( date ));

Upvotes: 5

Related Questions