- 实例化位于java.util的Date类,通过format转换格式。
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(simpleDateFormat.format(date));
运行结果图:
注意:HH要大写,否则时间不显示上午还是下午。
- 通过Util包的Calendar获取。
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(simpleDateFormat.format(calendar.getTime()));
- 通过System.currentTimeMillis() 方法来获取,不受时区的影响,得到结果是时间戳的格式,可通过format转换格式。
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(simpleDateFormat.format(System.currentTimeMillis()));