第一种:
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) {
//
// A string of time information
//
String time = "15:30:18";
//
// Create an instance of SimpleDateFormat with the specified
// format.
//
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);
System.out.println("Date and Time: " + date);
} catch (Exception e) {
e.printStackTrace();
}
}
}
第二种:
public static Time parseHHMM(String time)
{
Time t = new Time();
// if the format is not "HH:MM" we return null
try
{
String hours = time.substring(0, 2);
String minutes = time.substring(3);
t.hour = Integer.parseInt(hours);
t.minute = Integer.parseInt(minutes);
}
catch (Exception e) // TODO is this nice enough?
{
return null;
}
return t;
}