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

后端 未结 3 1718
一整个雨季
一整个雨季 2020-12-11 09:17

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 al

相关标签:
3条回答
  • 2020-12-11 09:30

    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;
            }
        }
    
    0 讨论(0)
  • 2020-12-11 09:38

    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?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    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.

    0 讨论(0)
  • 2020-12-11 09:38

    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

    0 讨论(0)
提交回复
热议问题