0

I am having various date String and want to format in particular format using java

String arr[] = {"Jul 02,2020 ","15-10-2015 10:20:56","2015/10/26 12:10:39","27-04-2016 10:22:56","April 7, 2020"};
    Arrays.asList(arr).forEach(date->{
        try {
            System.out.println(convertDate(date, "yyyy-MM-dd hh:mm:ss"));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    });

public static String getDateString(String date,String patternStr) throws ParseException {
    if(StringUtils.isNotEmpty(date)&& StringUtils.isNotEmpty(patternStr)) {
        SimpleDateFormat pattern = new SimpleDateFormat(patternStr);
        Date dateObject =new Date(date);
        return pattern.format(dateObject).toString();
    }
    return date;
}

But i am getting parse Exception for some of the date value.Is there any generic way to support for all the input date value .

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 2
    To go from "something of A" to "B" you need to know what format "something of A" is actually in, otherwise you're losing context which is required to ensure a valid conversation. A "common" approach to this kind of problem, is to have a "list" of "acceptable input formats", you'd then take each item and attempt to parse it against this list of "acceptable input formats" until either you get a successful result, or you run out of "acceptable input formats", which would represent an edge case to which you'd need to decide how to handle – MadProgrammer Jul 03 '20 at 04:05
  • 2
    [How to parse dates in multiple formats using SimpleDateFormat](https://stackoverflow.com/questions/4024544/how-to-parse-dates-in-multiple-formats-using-simpledateformat) – akuzminykh Jul 03 '20 at 04:07
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Even if you insisted on `Date`, you should still stay far away from the `Date(String)` constructor. It’s been deprecated since 1997 because it works unreliably across time zones. – Ole V.V. Jul 03 '20 at 05:15
  • For which strings do you get an incorrect result? In those cases what is the expected output? And the observed output? Please always give this information when asking about code that doesn’t work as expected. – Ole V.V. Jul 03 '20 at 05:18
  • @OleV.V. for `15-10-2015 10:20:56` – Raushan Setthi Jul 03 '20 at 05:33
  • **Did you mean: *`yyyy-MM-dd HH:mm:ss`*?** – MC Emperor Jul 03 '20 at 12:07
  • @Raushan Setthi consider using Joda-Time https://www.joda.org/joda-time/ , which uses a DateTimeFormatterBuilder() used to parse multiple patterns.https://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormatterBuilder.html#DateTimeFormatterBuilder-- –  Jul 03 '20 at 12:28
  • 1
    @VictorS While Joda-Time will be a giant step forward, we can make that step even greater by moving to [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Joda-Time is not being further developed anymore and has been officially replaced by java.time. – Ole V.V. Jul 04 '20 at 04:37
  • @OleV.V. good to note. Agreed with that point. –  Jul 04 '20 at 05:05

2 Answers2

4

I recommend you switch from the outdated and error-prone java.util date-time API to the rich set of modern date-time API. Using DateTimeFormatterBuilder, you can build a format including all expected date-time formats and hour, minute, second defaulting to 0.

Demo

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;

public class Main {
    public static void main(final String[] args) {
        String arr[] = { "Jul 02,2020 ", "15-10-2015 10:20:56", "2015/10/26 12:10:39", "27-04-2016 10:22:56",
                "April 7, 2020" };
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                        .appendPattern("[MMM d,yyyy]")
                                        .appendPattern("[dd-MM-yyyy HH:mm:ss]")
                                        .appendPattern("[yyyy/MM/dd HH:mm:ss]")
                                        .appendPattern("[dd-MM-yyyy HH:mm:ss]")
                                        .appendPattern("[MMMM d, yyyy]")
                                        .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                                        .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                                        .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                                        .toFormatter();

        for (String s : arr) {
            LocalDateTime ldt = LocalDateTime.parse(s.trim(), formatter);
            System.out.println("LocalDate#toString: " + ldt + ", " + "Formatted: "
                    + ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
    }
}

Output:

LocalDate#toString: 2020-07-02T00:00, Formatted: 2020-07-02 00:00:00
LocalDate#toString: 2015-10-15T10:20:56, Formatted: 2015-10-15 10:20:56
LocalDate#toString: 2015-10-26T12:10:39, Formatted: 2015-10-26 12:10:39
LocalDate#toString: 2016-04-27T10:22:56, Formatted: 2016-04-27 10:22:56
LocalDate#toString: 2020-04-07T00:00, Formatted: 2020-04-07 00:00:00
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 3
    This is a more modular and efficient approach. It's has been documented in many articles by now that SimpleDateFormat is notoriously prone to error. DateTimeFormatterBuilder here only creates a single instance to handle multiple patterns, with the added bonus of readability. –  Jul 03 '20 at 12:18
0

No way you can do that. For every Date string , you need to pass the pattern along with it. Else you have to build your own String parser which can be ugly and cumbersome.

First of all the constructor accepting String is deprecated as of JDK version 1.1, replaced by DateFormat.parse(String s).

Check the doc

The right way to parse date from string is:

String sDate1="31/12/1998";  
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
Abhinaba Chakraborty
  • 3,488
  • 2
  • 16
  • 37