how to convert string into time format and add two hours

后端 未结 9 1114
轻奢々
轻奢々 2020-12-13 05:04

I have the following requirement in the project.

I have a input field by name startDate and user enters in the format YYYY-MM-DD HH:MM:SS.

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 05:23

    Being a fan of the Joda Time library, here's how you can do it that way using a Joda DateTime:

    import org.joda.time.format.*;
    import org.joda.time.*;
    
    ...    
    
    String dateString = "2009-04-17 10:41:33";
    
    // parse the string
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime dateTime = formatter.parseDateTime(dateString);
    
    // add two hours
    dateTime = dateTime.plusHours(2); // easier than mucking about with Calendar and constants
    
    System.out.println(dateTime);
    

    If you still need to use java.util.Date objects before/after this conversion, the Joda DateTime API provides some easy toDate() and toCalendar() methods for easy translation.

    The Joda API provides so much more in the way of convenience over the Java Date/Calendar API.

提交回复
热议问题