Shashank
Shashank

Reputation: 7

Need to Format String Date in different format in java

I have a String date "30 Aug 2019". I want to format in "2019-08-30'. I am trying with following code. It is not working.

String input = "30 Aug 2019"; Date date = sdf.parse(input);

       // Date to String:
      String strDate = sdf.format(date);
      System.out.println(strDate);

I am getting an error as Exception in thread "main" java.text.ParseException: Unparseable date: "30 Aug 2019"

Please help me, how to go ahead ?

Upvotes: -2

Views: 103

Answers (2)

Bohemian
Bohemian

Reputation: 425318

Although you should use java.time classes, to answer your question, you need 2 SimpleDateFormats; one for parsing and one for formatting:

SimpleDateFormat sdfIn = new SimpleDateFormat("dd MMM yyyy");
SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd");

Date date = sdfIn.parse("30 Aug 2019");
String strDate = sdfOut.format(date);

System.out.println(strDate); // 2019-08-30

Upvotes: 0

Basil Bourque
Basil Bourque

Reputation: 340070

tl;dr

You are using terrible date-time classes that were outmoded years ago by the adoption of JSR 310. Use java.time.LocalDate instead.

And you neglected to specify a formatting pattern to match your input string. We do so here using the DateTimeFormatter class.

LocalDate
.parse(
    "30 Aug 2019" ,
    DateTimeFormatter.ofPattern( "d MMM uuuu" ).withLocale( Locale.US )
)
.toString()

2019-08-30

java.time

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

Specify a Locale on your DateTimeFormatter to determine the human language and cultural norms needed for translating name of month, and such.

String input = "30 Aug 2019" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d MMM uuuu" ).withLocale( Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

See this code run live at IdeOne.com.

ld.toString(): 2019-08-30


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.

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

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

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for 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.

Upvotes: 2

Related Questions