Java SimpleDateFormat parse String like "2018-04-03 09:10:40.325" to date

Description

Java SimpleDateFormat parse String like "2018-04-03 09:10:40.325" to date

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);/*from w w  w. j ava 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));

  }
}



PreviousNext

Related