How do I convert string of time to time object?

Category: java.util, viewed: 19647 time(s).
package org.kodejava.example.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToTimeExample
{
    public static void main(String[] args)
    {
        // You want to convert a string reprenting a time into a time object
        // in Java. As we know that Java is representing a time information
        // in a class java.util.Date, this class keep information about date
        // and time.
        String time = "15:30:18";

        // Now if you have a string of time you can use a SimpleDateFormat
        // object to parse the string date and return a date object. The pattern
        // of the string should be passed to the simple date format constructor.
        // In the example below the string is formatted as hh:mm:ss (hour:minutes:
        // second).
        DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
        try
        {
            // The get the date object from the string just called the parse 
            // method and pass the time string to it. The method throws ParseException
            // if the time string is in an invalid format. But remember as we don't
            // pass the date information this date object will represent the 1st of
            // january 1970.
            Date date = sdf.parse(time);
            
            // As the parse process success we'll have our time string in the
            // created date instance.
            System.out.println("Date and Time: " + date);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats