Java String to DateTime

后端 未结 3 1267
耶瑟儿~
耶瑟儿~ 2020-12-18 23:39

I have a string from a json response:

start: \"2013-09-18T20:40:00+0000\",
end: \"2013-09-18T21:39:00+0000\",

How do i convert this string

相关标签:
3条回答
  • 2020-12-19 00:03

    You can create Joda DateTime object from the Java Date object, since Java does not have a DateTime class.

    DateTime dt = new DateTime(start.getTime());
    

    Though the Date class of Java holds the time information as well(that's what you need in the first place), I suggest you to use a Calendar instead of the Date class of Java.

    Calendar myCal = new GregorianCalendar();
    myCal.setTime(date);
    

    Have a look at the Calendar docs for more info on how you can use it more effectively.


    Things have changed and now even Java (Java 8 to be precise), has a LocalDateTime and ZonedDateTime class. For conversions, you can have a look at this SO answer(posting an excerpt from there).

    Given: Date date = [some date]

    (1) LocalDateTime << Instant<< Date

    Instant instant = Instant.ofEpochMilli(date.getTime());
    LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
    

    (2) Date << Instant << LocalDateTime

    Instant instant = ldt.toInstant(ZoneOffset.UTC);
    Date date = Date.from(instant);
    
    0 讨论(0)
  • 2020-12-19 00:23

    You don't need a DateTime object. java.util.Date stores the time too.

    int hours = start.getHours(); //returns the hours
    int minutes = start.getMinutes(); //returns the minutes
    int seconds = start.getSeconds(); //returns the seconds
    

    As R.J says, these methods are deprecated, so you can use the java.util.Calendar class:

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(sdf.parse("2013-09-18T20:40:00+0000"));
    int hour = calendar.get(Calendar.HOUR); //returns the hour
    int minute = calendar.get(Calendar.MINUTE); //returns the minute
    int second = calendar.get(Calendar.SECOND); //returns the second
    

    Note: on my end, sdf.parse("2013-09-18T20:40:00+0000") fires a

    java.text.ParseException: Unparseable date: "2013-09-18T20:40:00+0000"
        at java.text.DateFormat.parse(DateFormat.java:357)
        at MainClass.main(MainClass.java:16)
    
    0 讨论(0)
  • 2020-12-19 00:30

    You can use DateTimeFormatter

    DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    DateTime time = format.parseDateTime("2013-09-18T20:40:00+0000");
    
    0 讨论(0)
提交回复
热议问题