SimpleDateFormat中parse和format的區別


parse()返回的是一個Date類型數據,format返回的是一個StringBuffer類型的數據

//SimpleDateFormat中的parse方法可以
//把String型的字符串轉換成特定格式的date類型
public static void main(String[] args) {  
        String str = "2013-01-21 15:10:20";  
        Date date = null;  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd-HH:mm:ss");  
        try {  
            date = sdf.parse(str);  
        } catch (ParseException e) {  
            System.out.println(e.getMessage());  
        }  
        System.out.println(date);  
        System.out.println(date.getTime());  
    }  
 

 


//SimpleDateFormat中的format方法可以
//把Date型的字符串轉換成特定格式的String類型

public static void main(String[] args){
 SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
 String a=dateformat.format(new Date());
 System.out.println("時間:"+a);
 
}
 
        

EX:

public class FormatDateTime {

public static void main(String[] args) {
SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒");
SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm"); 
SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//等價於now.toLocaleString()
SimpleDateFormat myFmt3=new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒 E ");
SimpleDateFormat myFmt4=new SimpleDateFormat(
"一年中的第 D 天 一年中第w個星期 一月中第W個星期 在一天中k時 z時區");
Date now=new Date();
System.out.println(myFmt.format(now));
System.out.println(myFmt1.format(now));
System.out.println(myFmt2.format(now));
System.out.println(myFmt3.format(now));
System.out.println(myFmt4.format(now));
System.out.println(now.toGMTString());
System.out.println(now.toLocaleString());
System.out.println(now.toString());
} 
}

SimpleDateFormat sdf = new SimpleDateFormat();String d = sdf.format(Date date);Date d = sdf.parse(String sourse);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM