import java.util.Calendar;import java.util.Date;//import java.sql.Date;public class date_01 { public static void main(String[] args) { // TODO Auto-generated method stub Date date =new Date(); System.out.println("年份:"+ date.getYear()); //横线表示已经过时的方法 Calendar calendar = Calendar.getInstance(); //获取当前的系统时间。 System.out.println("年:"+ calendar.get(Calendar.YEAR)); System.out.println("月:"+ (calendar.get(Calendar.MONTH)+1)); System.out.println("日:"+ calendar.get(Calendar.DATE)); System.out.println("时:"+ calendar.get(Calendar.HOUR_OF_DAY)); System.out.println("分:"+ calendar.get(Calendar.MINUTE)); System.out.println("秒:"+ calendar.get(Calendar.SECOND)); }}
运行结果:
年份:119年:2019月:6日:3时:21分:8秒:48
日期格式化类 SimpleDateFormat
public static void main(String[] args) throws ParseException { // 显示 当前系统时间: 2014年12月26日 xx时xx分xx秒 /* 日期格式化类 SimpleDateFormat * 作用1: 可以把日期转换转指定格式的字符串 format() * 作用2: 可以把一个 字符转换成对应的日期。 parse() 生日 */ Date date = new Date(); //获取当前的系统时间。 SimpleDateFormat dateFormat = new SimpleDateFormat() ; //使用了默认的格式创建了一个日期格式化对象。 String time = dateFormat.format(date); //可以把日期转换转指定格式的字符串 System.out.println("当前的系统时间:"+ time); //当前的系统时间:19-6-3 下午9:15 Date date1 = new Date(); //获取当前的系统时间。 SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss") ; //使用了自定义格式创建了一个日期格式化对象。 String time1 = dateFormat1.format(date1); //可以把日期转换转指定格式的字符串 System.out.println("当前的系统时间:"+ time1); //当前的系统时间:2019年06月03日 21:15:55 String birthday = "2010年6月8日 09:11:12"; Date date2 = dateFormat1.parse(birthday); //注意: 指定的字符串格式必须要与SimpleDateFormat的模式要一致,parse 这个是需要抛出异常的 System.out.println(date2); }
运行结果:
当前的系统时间:19-6-4 下午9:13当前的系统时间:2019年06月04日 21:13:29Tue Jun 08 09:11:12 CST 2010