简体   繁体   中英

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

    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

    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

    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?

I take it that the DateTime class you are using is 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). 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. The date-time classes you were using, Date and SimpleDateFormat , are long outdated, and the latter in particular notoriously troublesome. So I am avoiding them in my code. The modern API is so much nicer to work with.

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. Since AM and PM are hardly used in other languages than English, give an English-speaking locale.

Link: Oracle tutorial: Date Time explaining how to use java.time .

if you want to parse a date of Format: 2/21/2018 8:00 PM you have to Change the pattern to:

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

For more informations see the javadoc of SimpleDateFormat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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