日期在java代碼中使用的太多了,不過很多時候得到的是國際時間,而國際時間並不符合我們的要求,這裏提供一個可以將String或者Date類型的變量轉換爲我們所需的標準格式時間。
public class test{
public static void main(String[] args) throws Exception{
Format fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date today = new Date();
System.out.println("今天是:" + fm.format(today));
Calendar c = Calendar.getInstance();
c.setTime(today);
c.add(Calendar.DAY_OF_MONTH, 1);// 在今天的基礎上+1天/周/月
Date tomorrow = c.getTime();
System.out.println("明天是:" + fm.format(tomorrow));
String a="2013-12-02 21:22:22";
Date d=sdf.parse(a);
System.out.println("轉換之前的時間:"+d);
System.out.println("轉換之後的時間:"+fm.format(d));
}
}
對String類型的變量,先用SimpleDateFormat對象轉成date類型,再用Format轉爲標準格式
結果:
今天是:2013-10-09
明天是:2013-10-10