Do Thanh Tung Do Thanh Tung - 21 days ago 4
Java Question

Parse a String contain GregorianCalendar to Date with partern

How can I parse this



to type Date in Java.
My problem is it's a String and I don't know how to parse.


Considering that the String is the output of toString() from a GregorianCalendar object, as shown in the question, it contains all the information required to build the Date object.

Assuming that Google Guava is declared as a dependency:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

 * Converts the string provided to a Date object
 * @param input String output of toString() from a GregorianCalendar object
 * @return Date object
 * @throws ParseException When the values received are invalid
public Date convertGregorianCalendarStringOutputToDate(final String input) throws ParseException {

    // Parses the string received with a format of tuples key=value, separated by commas
    String formatted = input.replaceAll("\\]|\\/|\"","");
    formatted = formatted.replaceFirst("\\[", "");
    formatted = formatted.replaceAll("\\[", ",");

    // Creates a map of the key-values parsed
    Map<String, String> params = Splitter

    StringBuffer stringDate = new StringBuffer(params.get("YEAR"));
            .append(" ")

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd hh:mm:ss");

The parsing of the the key-values pair is taken from here