JAVA日期格式化直接使用SimpleDateFormat类,他提供了比较强大的日期转换格式可以日期转成字符串,也可以把字符串转成日期
运行结果:
- import java.util.Date;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- public class SampleDateFamat {
- public static void main(String[] args) {
- SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date date1 = new Date();
- String str1 = sd.format(date1);
- System.out.println(str1);
- SimpleDateFormat sd2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
- String str2 = sd2.format(date1);
- System.out.println(str2);
- try {
- SimpleDateFormat sd3 = new SimpleDateFormat("yyyyMMdd");
- Date date2 = sd3.parse("20090425");
- System.out.print(date2);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- }
- }
import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; public class SampleDateFamat { public static void main(String[] args) { SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date1 = new Date(); String str1 = sd.format(date1); System.out.println(str1); SimpleDateFormat sd2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String str2 = sd2.format(date1); System.out.println(str2); try { SimpleDateFormat sd3 = new SimpleDateFormat("yyyyMMdd"); Date date2 = sd3.parse("20090425"); System.out.print(date2);} catch (ParseException e) { e.printStackTrace();}}}
运行结果:
- 2009-09-04 16:01:21
- 2009-09-04 04:01:21
- Sat Apr 25 00:00:00 CST 2009