Getting a date object from a string

Posted on 2006-05-25
Last Modified: 2010-03-31
I have a string object.

String s = "2006-05-11 17:04:28.000"

How can I create a date object from that string?

I tried Date date = new Date(s);

But that looks like a deprecated method. What is the best way ?

thanks in advance

Question by:expertsit
    LVL 86

    Accepted Solution

    Use a DateFormat

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    Date d = df.parse("2006-05-11 17:04:28.000");

    Author Comment

    Thanks that worked.
    LVL 86

    Expert Comment

    LVL 3

    Expert Comment

    You can try:

    strFormat = "2006-05-11 17:04:28.000";
    DateFormat myDateFormat = new SimpleDateFormat(strFormat);
    Date myDate = null;
    try {
         myDate = myDateFormat.parse(strDate);
    } catch (ParseException e) {
         System.out.println("Invalid Date Parser Exception ");
    System.out.println("Finished Date Function " + myDate.getDay());

    Author Comment

    Thanks for your response.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Should I Do With This Threat Intelligence?

    Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

    Suggested Solutions

    An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
    By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
    This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
    This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now