w3resource

Java: Extract date, time from the date string


35. Extract Date and Time

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

Sample Solution:

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

Pictorial Presentation:

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


Flowchart:

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


For more Practice: Solve these Related Problems:

  • Write a Java program to parse a complex date-time string and extract the date and time components separately.
  • Write a Java program to split a date-time string into its date and time parts using substring methods.
  • Write a Java program to extract and display the date and time from a formatted date string using regex.
  • Write a Java program to convert a date-time string into two separate variables for date and time and print them.

Go to:


PREV : Today at Midnight.
NEXT : Unix Timestamp to Date.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.