Extract time from date String

Extract time from date String

Asked on January 2, 2019 in Java.
Add Comment


  • 5 Answer(s)

    The conversion between a date string and a Date object can be done by SimpleDateFormat . Take a Date as a beginning point. There are lot of patterns in the javadoc of SimpleDateFormat.

    Hava a look at the example,

    String originalString = "2010-07-14 09:00:02";
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
    String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
    
    Answered on January 2, 2019.
    Add Comment

    One can achieve the solution by using this code ,

    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
    String time = new SimpleDateFormat("H:mm").format(date);
    
    Answered on January 2, 2019.
    Add Comment

    By using a SimpleDateFormatter , we can get the solution easily.

    Answered on January 2, 2019.
    Add Comment

    If you have date in integers, you could use like here:

    Date date = new Date();
    date.setYear(2010);
    date.setMonth(07);
    date.setDate(14)
    date.setHours(9);
    date.setMinutes(0);
    date.setSeconds(0);
    String time = new SimpleDateFormat("HH:mm:ss").format(date);
    Answered on January 16, 2019.
    Add Comment

    The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormatget replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:

        String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
                .format(DateTimeFormatter.ofPattern("H:mm"));

    The result is the desired, 9:00.

    Answered on January 16, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.