【JAVA】之【string转time方法】

来源:互联网 发布:数据库作图软件 编辑:程序博客网 时间:2024/05/21 19:46

第一种:

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(02);
            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;
    }


原创粉丝点击