How to initialize a variable of date type in java?

前端 未结 5 2176
萌比男神i
萌比男神i 2021-02-20 03:04
import java.util.Date;
Date firstDate; 

I don\'t know how to intialize the firstDate for example for String you say

String line1=\"Fir         


        
5条回答
  •  星月不相逢
    2021-02-20 03:36

    To parse a Date from a String you can choose which format you would like it to have. For example:

    public Date StringToDate(String s){
    
        Date result = null;
        try{
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            result  = dateFormat.parse(s);
        }
    
        catch(ParseException e){
            e.printStackTrace();
    
        }
        return result ;
    }
    

    If you would like to use this method now, you will have to use something like this

    Date date = StringToDate("2015-12-06 17:03:00");
    

    For more explanation you should check out http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

提交回复
热议问题