subhashis
subhashis

Reputation: 4878

How to convert string of type YY/MM/DD to java.util.Date?

I have searched but did not find the exact format(YY/MM/DD) for parsing the String.

How can I convert a string of type YY/MM/DD to java.util.Date. I have strings in the format "160310", "160211".

Upvotes: 1

Views: 2299

Answers (6)

Basil Bourque
Basil Bourque

Reputation: 338654

Formatting pattern must match input

You said:

How can I convert a string of type YY/MM/DD … I have strings in the format "160310", "160211".

You do not have strings of YY/MM/DD. Your input strings have no slash character (/). Define a formatting pattern to match your actual inputs.

java.time

Use only java.time classes in modern Java.

Define your formatting pattern. A century of 20xx is assumed by default.

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uu/MM/dd" ) ;
LocalDate ld = LocalDate.parse ( input , f ) ;

Detect invalid inputs by trapping for DateTimeParseException.

Upvotes: 1

mtj
mtj

Reputation: 3554

If you have reached the area of Java 8, you might also consider

        Date dt = Date.valueOf(LocalDate.from(DateTimeFormatter.ofPattern("yyMMdd").parse("160123")));

But in fact, you would not do the conversion to the old ugly date if you can avoid it, but rather go along with the LocalDate you created on your way.

Upvotes: 2

Rishal
Rishal

Reputation: 1538

Use the following code , It will

    String mydate="160310";
    SimpleDateFormat sd=new SimpleDateFormat("YYmmdd",Locale.ENGLISH);
    Date date = sd.parse(mydate);
    System.out.println(date);`

Upvotes: 1

Tim
Tim

Reputation: 4274

Like this:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTester {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");

        Date date = null;
        try {
            date = sdf.parse("160310");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(date);
    }
}

Upvotes: -1

Jur Clerkx
Jur Clerkx

Reputation: 698

You can use SimpleDateFormat for this.

String target = "160211";
DateFormat df = new SimpleDateFormat("yyMMdd", Locale.ENGLISH);
Date result =  df.parse(target);

For more options and info you can always checkout the full documentation about it here: http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html

Upvotes: 9

Mureinik
Mureinik

Reputation: 311373

Nit: The format isn't "YY/MM/DD", it's "YYMMDD" (note the slashes). Regardless, you can use a SimpleDateFormat to parse such strings:

DateFormat df = new SimpleDateFormat("yyMMdd");
Date date = df.parse("160211");

Upvotes: 1

Related Questions