解析一个包含 GregorianCalendar 到 Date 的字符串

Parse a String contain GregorianCalendar to Date with partern

我该如何解析这个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]

在 Java 中输入日期。 我的问题是它是一个字符串,我不知道如何解析。

考虑到字符串是 GregorianCalendar 对象的 toString() 的输出,如问题所示,它包含构建 Date 对象所需的所有信息。

假设 Google Guava 被声明为依赖:

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()));
}

键值对的解析取自here