Convert String to Date

In this chapter you will learn:

  1. How to parse string to get Date

Parse string to get Date

DateFormat class has the following methods we can use to convert string value to Date value.

  • Date parse(String source)
  • parses text from the beginning of the given string to produce a date.
  • Object parseObject(String source, ParsePosition pos) parses text from a string to produce a Date.
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
//j  av a  2 s .co m
public class Main{
  public static void main(String args[]) {
    Date d = null;
    try {
      d = DateFormat.getDateInstance().parse("18-Nov-2010");
    } catch (ParseException e) {
      e.printStackTrace();
    }
    System.out.println(d);
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What is Java SimpleDateFormat for
  2. What are date and time Patterns for SimpleDateFormat
  3. Repeat letters to create format