Search code examples
javadategregorian-calendar

Parse a String contain GregorianCalendar to Date with partern


How can I parse this String

java.util.GregorianCalendar[time=1461732800330,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Tokyo",offset=32400000,dstSavings=0,useDaylight=false,transitions=10,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=3,WEEK_OF_YEAR=18,WEEK_OF_MONTH=5,DAY_OF_MONTH=27,DAY_OF_YEAR=118,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=53,SECOND=20,MILLISECOND=330,ZONE_OFFSET=32400000,DST_OFFSET=0]

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


Solution

  • 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 com.google.common.base.Splitter;
    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
                    .on(",")
                    .withKeyValueSeparator("=")
                    .split(formatted);
    
        StringBuffer stringDate = new StringBuffer(params.get("YEAR"));
        stringDate.append("-")
                .append(params.get("MONTH"))
                .append("-")
                .append(params.get("DAY_OF_MONTH"))
                .append(" ")
                .append(params.get("HOUR_OF_DAY"))
                .append(":")
                .append(params.get("MINUTE"))
                .append(":")
                .append(params.get("SECOND"));
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd hh:mm:ss");
        return(sdf.parse(stringDate.toString()));
    }
    

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