简体   繁体   English

在 Spring 中将字符串解析为日期格式

[英]Parse String to Date format in Spring

I am trying to update google calendar event start and end datetime in spring class.But i am getting DateFormat exception.I am able to get particular event and display in modal popup.I am using kendo directives datepicker.Now if the user edits the start and end date it is getting changed in this format我正在尝试更新 spring 类中的谷歌日历事件开始和结束日期时间。但我收到 DateFormat 异常。我能够获取特定事件并在模式弹出窗口中显示。我正在使用剑道指令 datepicker。现在如果用户编辑开始和结束日期正在以这种格式更改

    String start=2/21/2018 8:00 PM
    String end:2/22/2018 9:00 PM

Now i am trying to set these dates for google event start and endDate like this in my class现在我正在尝试在我的课堂上像这样为谷歌事件开始和结束日期设置这些日期

ServiceImpl.java ServiceImpl.java

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    try {
        Date d = sdf.parse(start);//2/21/2018 8:00 PM
        Date end = sdf.parse(end);//2/22/2018 9:00 PM
        event.setStart(new EventDateTime().setDateTime(new DateTime(d)));
        event.setEnd(new EventDateTime().setDateTime(new DateTime(end)));
        // Update the event
        Event updatedEvent = service.events().patch("primary", googleEventDto.getEventId(), event).execute();
    } catch (ParseException e)
    {
        // execution will come here if the String that is given
        // does not match the expected format.
        e.printStackTrace();
    }

But i am getting exception Unparseable date 2/21/2018 8:00 PM.But if set directly like this但是我收到异常 Unparseable date 2/21/2018 8:00 PM。但是如果像这样直接设置

    event.setStart(new EventDateTime().setDateTime(new DateTime("2018-02-28T07:00:00.000+05:30")));
    event.setStart(new EventDateTime().setDateTime(new DateTime("2018-02-28T09:00:00.000+05:30")));

It is working perfectly.Can anyone tell how can i parse date 2/21/2018 8:00 into this format 2018-02-21T08:00:00.000+05:30?它工作得很好。谁能告诉我如何将日期 2/21/2018 8:00 解析为这种格式 2018-02-21T08:00:00.000+05:30?

I take it that the DateTime class you are using is com.google.api.client.util.DateTime .我认为您使用的DateTime类是com.google.api.client.util.DateTime If so the following method will solve your issue:如果是这样,以下方法将解决您的问题:

private static final DateTimeFormatter userDateTimeFormatter 
        = DateTimeFormatter.ofPattern("M/d/uuuu h:mm a", Locale.ENGLISH);
private static final ZoneId zone = ZoneId.of("Asia/Kolkata");

private static DateTime parseToGoogleDateTime(String userDateTime) {
    long millis = LocalDateTime.parse(userDateTime, userDateTimeFormatter)
            .atZone(zone)
            .toInstant()
            .toEpochMilli();
    return new DateTime(millis);
}

Use like this:像这样使用:

    try {
        DateTime startDateTime = parseToGoogleDateTime(start); //2/21/2018 8:00 PM
        DateTime endDateTime = parseToGoogleDateTime(end); //2/22/2018 9:00 PM
        event.setStart(new EventDateTime().setDateTime(startDateTime));
        event.setEnd(new EventDateTime().setDateTime(endDateTime));
        // Update the event
        Event updatedEvent = service.events().patch("primary", googleEventDto.getEventId(), event).execute();
    } catch (DateTimeParseException dtpe) {
        // execution will come here if the String that is given
        // does not match the expected format.
        dtpe.printStackTrace();
    }

EDIT: I understand that your date-time string may also come like 2018-02-28T07:00:00.000+05:30 (ISO 8601 format).编辑:我知道你的日期时间字符串也可能像2018-02-28T07:00:00.000+05:30 (ISO 8601 格式)。 You may want to see if you can fix it so only one format is possible;您可能想看看是否可以修复它,以便只有一种格式是可能的; but if not, just try parsing both formats in turn until one works:但如果没有,请尝试依次解析两种格式,直到一种有效:

private static DateTime parseToGoogleDateTime(String userDateTime) {
    long millis;
    try {
        // try to parse fprmat like 2018-02-28T07:00:00.000+05:30
        millis = OffsetDateTime.parse(userDateTime)
                .toInstant()
                .toEpochMilli();
    } catch (DateTimeParseException dtpe) {
        // instead try like 2/21/2018 8:00 PM
        millis = LocalDateTime.parse(userDateTime, userDateTimeFormatter)
                .atZone(zone)
                .toInstant()
                .toEpochMilli();
    }
    return new DateTime(millis);
}

I am using and warmly recommending java.time, the modern Java date and time API.我正在使用并热烈推荐 java.time,现代 Java 日期和时间 API。 The date-time classes you were using, Date and SimpleDateFormat , are long outdated, and the latter in particular notoriously troublesome.您使用的日期时间类DateSimpleDateFormat早已过时,而后者尤其麻烦。 So I am avoiding them in my code.所以我在我的代码中避免使用它们。 The modern API is so much nicer to work with.现代 API 更易于使用。

Please substitute your desired time zone if it didn't happen to be Asia/Kolkata.如果不是亚洲/加尔各答,请替换您想要的时区。 You may use ZoneId.systemDefault() for the JVM's time zone setting, just know that the setting may be changed by other parts of your program or other programs running in the same JVM.您可以将ZoneId.systemDefault()用于 JVM 的时区设置,只要知道该设置可能会被程序的其他部分或在同一 JVM 中运行的其他程序更改。 Since AM and PM are hardly used in other languages than English, give an English-speaking locale.由于 AM 和 PM 几乎不用于英语以外的其他语言,因此请提供英语语言环境。

Link: Oracle tutorial: Date Time explaining how to use java.time .链接: Oracle 教程:解释如何使用java.time的日期时间。

if you want to parse a date of Format: 2/21/2018 8:00 PM you have to Change the pattern to:如果你想解析格式的日期:2/21/2018 8:00 PM 你必须将模式更改为:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm a");

For more informations see the javadoc of SimpleDateFormat有关更多信息,请参阅SimpleDateFormat 的 javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM