-3

I want to convert String values in the format of mm/dd/yy to YYYY-MM-DD Date. how to do this conversion?

The input parameter is: 03/01/18

Code to convert String to Date is given below

public static Date stringToDateLinen(String dateVlaue) {
    Date date = null;
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    try {

        date = formatter.parse(dateVlaue);

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

When tried to convert using this method it shows the following error

java.text.ParseException: Unparseable date: "03/01/18"
MT0
  • 143,790
  • 11
  • 59
  • 117
S Mugunthan kumar
  • 177
  • 1
  • 2
  • 11
  • Just check your input date and the date format you are using, are they matching? Try it yourself, don't look for answer – Hemant Patel May 18 '18 at 06:40
  • 4
    Just so we're clear, `Date` DOES NOT have a concept of format, it's just a container for the number of milliseconds since the Unix epoch. To get over your "error", the format for the parse needs to be the same as the input – MadProgrammer May 18 '18 at 06:41
  • 1
    I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 18 '18 at 07:20
  • 1
    As Ole V.V. commented, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/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/10/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 May 20 '18 at 20:10

5 Answers5

3

As you say the input is in a different format, first convert the String to a valid Date object. Once you have the Date object you can format it into different types , as you want, check.

To Convert as Date,

SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
date = formatter.parse(dateVlaue);

To Print it out in the other format,

SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date)
Antho Christen
  • 1,369
  • 1
  • 10
  • 21
0

You are writing it the wrong way. In fact, for the date you want to convert, you need to write SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");

DamCx
  • 1,047
  • 1
  • 11
  • 25
0

The format you are passing to SimpleDateFormat is ("yyyy-MM-dd") which expects date to be in form 2013-03-01 and hence the error.

You need to supply the correct format that you are passing your input as something like below

public static Date stringToDateLinen(String dateVlaue) {
    Date date = null;
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");

    try {

        date = formatter.parse(dateVlaue);

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}
piy26
  • 1,574
  • 11
  • 21
0

The solution for the above problem

  1. Convert the String date value in the Format of "dd/mm/yy" to Date.
  2. By using the converted Date can able to frame the required date format.

The method has given below

public static String stringToDateLinen(String dateVlaue) {
    Date date = null;
    SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yy");
    String dateString = null;
    try {
        // convert to Date Format From "dd/mm/yy" to Date
        date = formatter.parse(dateVlaue);
        // from the Converted date to the required format eg : "yyyy-MM-dd"
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
        dateString = formatter1.format(date);

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateString;
}
S Mugunthan kumar
  • 177
  • 1
  • 2
  • 11
  • Thanks for sharing your solution! It still doesn’t work, sorry. I thought that 03/01/18 meant March 1, but your method returns 2018-01-03, that is, January 3. If I feed it `12/24/18`, I get `2018-01-12`, the month is `01` every time. `24/12/18` becomes `2018-01-24`. – Ole V.V. May 18 '18 at 09:58
  • Actual out put format need is YYY-MM-DD, but my input format is dd/mm/yy as string – S Mugunthan kumar May 22 '18 at 05:50
  • dd/mm/yy disagrees with your question. You may want to [edit the question](https://stackoverflow.com/posts/50405211/edit) to make it clear. – Ole V.V. May 22 '18 at 06:09
  • I have edited my answer to reflect – Ole V.V. May 22 '18 at 10:13
0

EDIT: Your question said “String values in the format of mm/dd/yy”, but I understand from your comments that you meant “my input format is dd/mm/yy as string”, so I have changed the format pattern string in the below code accordingly. Otherwise the code is the same in both cases.

public static Optional<LocalDate> stringToDateLinen(String dateValue) {
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
    try {
        return Optional.of(LocalDate.parse(dateValue, dateFormatter));
    } catch (DateTimeParseException dtpe) {
        return Optional.empty();
    }
}

Try it:

    stringToDateLinen("03/01/18")
            .ifPresentOrElse(System.out::println, 
                    () -> System.out.println("Could not parse"));

Output:

2018-01-03

I recommend you stay away from SimpleDateFormat. It is long outdated and notoriously troublesome too. And Date is just as outdated. Instead use LocalDate and DateTimeFormatter from java.time, the modern Java date and time API. It is so much nicer to work with. A LocalDate is a date without time of day, so this suites your requirements much more nicely than a Date, which despite its name is a point in time. LocalDate.toString() produces exactly the format you said you desired (though the LocalDate doesn’t have a format in it).

My method interprets your 2-digit year as 2000-based, that is, from 2000 through 2099. Please think twice before deciding that this is what you want.

What would you want to happen if the string cannot be parsed into a valid date? I’m afraid that returning null is a NullPointerException waiting to happen and a subsequent debugging session to track down the root cause. You may consider letting the DateTimeParseException be thrown out of your method (just declare that in Javadoc) so the root cause is in the stack trace. Or even throw an AssertionError if the situation is not supposed to happen. In my code I am returning an Optional, which clearly signals to the caller that there may not be a result, which (I hope) prevents any NullPointerException. In the code calling the method I am using the ifPresentOrElse method introduced in Java 9. If not using Java 9 yet, use ifPresent and/or read more about using Optional elsewhere.

What went wrong in your code?

The other answers are correct: Your format pattern string used for parsing needs to match the input (not your output). The ParseException was thrown because the format pattern contained hyphens and the input slashes. It was good that you got the exception because another problem is that the order of year, month and day doesn’t match, neither does the number of digits in the year.

Link

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161