使用 Date 类的默认无参构造方法创建出的对象就代表当前时间,我们可以直接输出 Date 对象显示当前的时间,显示的结果如下:
public static void main(String[] args){ Date date = new Date(); System.out.println(date); // Mon Feb 11 21:58:30 CST 2019 }
//转换时格式间 Date和SimpleDateFormat //yyyy 表示四位年, MM 表示两位月份, dd 表示两位日期, HH 表示小时(使用24小时制), mm 表示分钟, ss 表示秒 // 使用 format() 方法将日期转换为指定格式的文本 Date datenow = new Date(); SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss"); System.out.println(ft.format(datenow));
注意:
1、 调用 SimpleDateFormat 对象的 parse() 方法时可能会出现转换异常,即 ParseException ,因此需要进行异常处理
2、 使用 Date 类时需要导入 java.util 包,使用 SimpleDateFormat 时需要导入 java.text
示例代码:
public static void main(String[] args){ // 使用format()方法将日期转换为指定格式的文本 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm"); SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 创建Date对象,表示当前时间 Date now = new Date(); // 调用format()方法,将日期转换为字符串并输出 System.out.println(sdf1.format(now));//2019年02月11日 21时50分48秒 System.out.println(sdf2.format(now));//2019/02/11 21:50 System.out.println(sdf3.format(now));//2019-02-11 21:50:48 // 使用parse()方法将文本转换为日期 String d = "2019-2-11 21:50:36"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 调用parse()方法,将字符串转换为日期 try { //注意一定要和指定的格式匹配 Date date =sdf.parse(d); System.out.println(date);//Mon Feb 11 21:50:36 CST 2019 }catch(ParseException e){ e.printStackTrace(); } }