Samstag, 11. Juli 2015

Date conversion in Java SE8

Date conversion between string-formats in Java SE 8

Requirements

Date conversion is in some cases nice to have for different countries and regions. It can also be a technical must have for database comparasion or storing content into date fields. Before Java SE8, there are many SimpleDateFormat examples outside. The following solution is oriented to SE8.
A basic requirement is to deal with string input and output to assign to JPA i.e.

The method should change a string from the example date "03.07.2014" to string "2014-07-03".

Solution

The script is a complete static solution to drag'n'drop into a new Java class. There are only basic operations and SE8 java.time.LocalDate and import java.time.format.DateTimeFormatter classes.

package DateConPackage;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateCon
{
    public static String value2QueryDate(String dateValue, 
                                         String inpattern, 
                                         String outpattern)
    {
        String              ret;
      
        DateTimeFormatter   dateFormatValue = 
                            DateTimeFormatter.ofPattern(inpattern);
        LocalDate           localDateValue  = 
                            LocalDate.parse(dateValue, dateFormatValue);

        ret =  localDateValue.format
               (
                    DateTimeFormatter.ofPattern(outpattern)
               );

        return ret;
    }
}


Script 1: DateCon.java


Example

In order to use it right, the date format has also to be considered. In most cases, day, month and year are fitting most cases. There are more detailed information for time and so on right here http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Date "03.07.2014" results to pattern "dd-MM-yyyy" and "2014-07-03" to "yyyy-MM-dd". The capital letters for month "MM" are mandatory.

package DateConPackage;


public class DateConExample
{
    public static void main(String[] args)
    {
        String fromdate = "03.07.2014";
        String todate   = "";
      
        todate = DateCon.value2QueryDate(fromdate,
                                         "dd.MM.yyyy",
                                         "yyyy-MM-dd");
      
        System.out.println(   "Inputdate: "
                            + fromdate
                            + " Outputdate: "
                            + todate);
    }

}

Script 2: DateConExample.java

Output

Running Script 2: DateConExample.java shows the result to the system output.

Inputdate: 03.07.2014 - Outputdate: 2014-07-03

Keine Kommentare:

Kommentar veröffentlichen