Convert date string to a particular date format "dd-MM-yyyy" in Java

55,695

Solution 1

ISO 8601

Now the problem is all contacts have different birthday formats

That is the real problem: storing date-time values in various formats.

When serializing date-time values to text, always use standard ISO 8601 formats. These formats are sensible and practical, avoiding ambiguity, being easy to parse by machine as well as readably by humans across cultures.

The java.time classes use these standard formats by default when parsing/generating strings.

java.time

The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes. Avoid the legacy Date, Calendar, SimpleDateFormat, and related classes.

So for example, one synchronized contact has birthday like "1990-02-07" or "1988-06-15T22:00:00.000Z" or "12-02-1990" etc...

Parsing any conceivable date-time format is impossible because of ambiguity. For example, is 01-02-1990 representing January 2nd or February 1st?

You can guess if you wish, though this may be ill-advised depending on how important accuracy means to your business problem.

Define a bunch of formatting patterns with DateTimeFormatter. Try each. When the DateTimeParseException is thrown, move on to the next pattern until one works.

You can use string length to help guide the guessing.

List < DateTimeFormatter > dateFormatters = new ArrayList <>( 2 );
dateFormatters.add( DateTimeFormatter.ofPattern( "uuuu-MM-dd" ) );  // BEWARE of ambiguity in these formatters regarding month-versus-day.
dateFormatters.add( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) );

String input = "1990-02-07";
// String input = "12-02-1990" ;

if ( null == input )
{
    throw new IllegalArgumentException( "Passed null argument where a date-time string is expected. Message # c7a4fe0e-9500-45d5-a041-74d457381008." );
} else if ( input.length() <= 10 )
{
    LocalDate ld = null;
    for ( DateTimeFormatter f : dateFormatters )
    {
        try
        {
            ld = LocalDate.parse( input , f );
            System.out.println( ld );
        } catch ( Exception e )
        {
            // No code here.
            // We purposely ignore this exception, moving on to try the next formatter in our list.
        }
    }
} else if ( ( input.length() > 10 ) && input.substring( input.length() - 1 ).equalsIgnoreCase( "Z" ) ) // If over 10 in length AND ends in a Z.
{
    Instant ld = null;
    try
    {
        ld = Instant.parse( input );  // Uses `DateTimeFormatter.ISO_INSTANT` formatter.
    } catch ( Exception e )
    {
        throw new IllegalArgumentException( "Unable to parse date-time string argument. Message # 0d10425f-42f3-4e58-9baa-84ff949e9574." );
    }
} else if ( input.length() > 10 )
{
    // TODO: Define another list of formatters to try here.
} else if ( input.length() == 0 )
{
    throw new IllegalArgumentException( "Passed empty string where a date-time string is expected. Message # 0ffbd9b6-8905-4e28-a732-0f402d4673df." );
} else  // Impossible-to-reach, for defensive programming.
{
    throw new RuntimeException( "ERROR - Unexpectedly reached IF-ELSE when checking input argument. Message # 6228d9e0-047a-4b83-8916-bc526e0fd22d." );
}
System.out.println("Done running.");

1990-02-07

Done running.


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.

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

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

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.

Solution 2

Simply using SimpleDateFormat class. Something like:

Date d = Calendar.getInstance().getTime(); // Current time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // Set your date format
String currentData = sdf.format(d); // Get Date String according to date format

Here you can see details and all supported format:

http://developer.android.com/reference/java/text/SimpleDateFormat.html

Solution 3

I somehow understand what you're problem is here. You can try the long way like splitting the strings with "-" and store it in array then check each string in the array, parse it to int then perform conditional statements.

assuming that the ones you gave has the following formats "1990-02-07" year-month-day "1988-06-15T22:00:00.000Z" year-month-dayTtimeZ "12-02-1990" month-day-year

you can try something like this.

    public String convert(String s){
        SimpleDateFormat newformat = new SimpleDateFormat("dd-MM-yyyy");
        try{
            if(s.contains("T")){
                String datestring = s.split("T")[0];
                SimpleDateFormat oldformat = new SimpleDateFormat("yyyy-MM-dd");
                String reformattedStr = newformat.format(oldformat.parse(datestring));
                return reformattedStr;
            }
            else{
                if(Integer.parseInt(s.split("-")[0])>13){
                    SimpleDateFormat oldformat = new SimpleDateFormat("yyyy-MM-dd");
                    String reformattedStr = newformat.format(oldformat.parse(s));
                    return reformattedStr;
                }
                else{
                    SimpleDateFormat oldformat = new SimpleDateFormat("MM-dd-yyyy");
                    String reformattedStr = newformat.format(oldformat.parse(s));
                    return reformattedStr;
                }

            }
        }
        catch (Exception e){
            return null;
        }
    }
Share:
55,695
Rushabh Patel
Author by

Rushabh Patel

Java and Android Developer SOreadytohelp

Updated on March 27, 2020

Comments

  • Rushabh Patel
    Rushabh Patel about 4 years

    I have multiple contacts with birth dates and all are synced with the mobile device. Now the problem is all contacts have different birthday formats and I want to display all of the birthday dates in a specific format like "dd-MM-yyyy".

    So for example, one synchronized contact has birthday like "1990-02-07" or "1988-06-15T22:00:00.000Z" or "12-02-1990" etc... Then all of these dates should be displayed in a specific format "dd-MM-yyyy".

    So how can I resolve this issue?

    Any suggestion will be appreciated.

  • Rushabh Patel
    Rushabh Patel over 11 years
    I am able to convert the given string to date in specific format as below if i know the original date string format . But how do i do this if i am not aware of the original string format.
  • Rushabh Patel
    Rushabh Patel over 11 years
    I am able to convert the given string to date in specific format as below if i know the original date string format . But how do i do this if i am not aware of the original string format.
  • Leonid
    Leonid over 11 years
    well, I guess you have to know the format of those being synchronized man. Check this one stackoverflow.com/questions/9291176/… I believe that month ALWAYS goes before day. you have three final formats here which are: month-day-year , year-month-day and year-month-dayTtimeZ.
  • Leonid
    Leonid over 11 years
    in the previous comment I said the month always goes before day. that's for anything that comes from java. And, I have edited my answer. you can try that one out...
  • kinghomer
    kinghomer over 11 years
    Well, if you specify a string format, SimpleDateFormat class should be complete missing part of Date with 'zero'. Take a proof
  • Basil Bourque
    Basil Bourque about 6 years
    FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.