w3resource logo


Java Programming Exercies

Java DateTime, Calendar Exercises: Extract date, time from the date string

Secondary Nav

Java DateTime, Calendar : Exercise-35 with Solution

Write a Java program to extract date, time from the date string.

Java Code:

import java.util.*;
import java.text.*;

public class Exercise35 {
  public static void main(String[] args)
   {
    try {    
      String originalString = "2016-07-14 09:00:02";
      Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
      String newstr = new SimpleDateFormat("MM/dd/yyyy, H:mm:ss").format(date);
       System.out.println("\n"+newstr+"\n");
      } 
    catch (ParseException e) {
    //Handle exception here
     e.printStackTrace();
     }
    }
}

Sample Output :

07/14/2016, 9:00:02 

Java Practice online:

import java.util.*;
import java.text.*;

public class Exercise35 {
  public static void main(String[] args)
   {
    try {    
      String originalString = "2016-07-14 09:00:02";
      Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
      String newstr = new SimpleDateFormat("MM/dd/yyyy, H:mm:ss").format(date);
       System.out.println("\n"+newstr+"\n");
      } 
    catch (ParseException e) {
    //Handle exception here
     e.printStackTrace();
     }
    }
}



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number