Java - Parse text that contains date and time.

Introduction

Suppose you have the text "2018-04-03 09:10:40.325", which represents a timestamp in the format year-month-day hour:minute:second.millisecond.

You want to get the time parts of the timestamp.

The following code shows how to get time parts from this text.

Demo

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
  public static void main(String[] args) {
    String input = "2018-04-03 09:10:40.325";

    // Prepare the pattern
    String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);

    // Parse the text into a Date object
    Date dt = sdf.parse(input, new ParsePosition(0));
    System.out.println(dt);//w  w w. j a v a  2  s.  c  o m

    // Get the Calendar instance
    Calendar cal = Calendar.getInstance();

    // Set the time
    cal.setTime(dt);

    // Print time parts
    System.out.println("Hour:" + cal.get(Calendar.HOUR));
    System.out.println("Minute:" + cal.get(Calendar.MINUTE));
    System.out.println("Second:" + cal.get(Calendar.SECOND));
    System.out.println("Millisecond:" + cal.get(Calendar.MILLISECOND));

  }
}

Result

Related Topic