Java09-获取当前日期的3种方式
package doudou; import java.util.Date; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; public class test_date { public static void main(String[] args) { System.out.println("============方式一:Date=========================="); Date a = new Date(); int current_year = a.getYear() + 1900; int current_month = a.getMonth() + 1; System.out.println("当前年:" + current_year); System.out.println("当前月:" + current_month);// Expired 月份 从0开始 System.out.println("当前日:" + a.getDate());// Expired 日 System.out.println("当前日期及时间: " + a.toString()); // 当前日期及时间 System.out.println(a.getClass());// 通过对象a调用getClass()方法返回Class System.out.println("============方式二:SimpleDateFormat和DateTimeFormatter=========================="); // 格式化时间(SimpleDateFormat和DateTimeFormatter) System.out.println("!!!!SimpleDateFormat:线程不安全!!!!"); Date date = new Date(); String strDateFormat = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat("当前日期及时间: " + strDateFormat); System.out.println(sdf.format(date)); String strDateFormat1 = "yyyy-MM-dd"; SimpleDateFormat sdf1 = new SimpleDateFormat("当前日期: " + strDateFormat1); System.out.println(sdf1.format(date)); String strDateFormat2 = "HH:mm:ss"; SimpleDateFormat sdf2 = new SimpleDateFormat("当前时间: " + strDateFormat2); System.out.println(sdf2.format(date)); System.out.println("!!!!DateTimeFormatter-LocalDateTime:线程安全!!!!"); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); System.out.println("当前日期及时间: " + dtf.format(LocalDateTime.now())); LocalDate localDate = LocalDate.now(); System.out.println("当前日期:" + localDate.toString()); LocalTime localTime = LocalTime.now().withNano(0);//去掉毫秒 System.out.println("当前时间:" +localTime.toString()); System.out.println("==============方式三:Calendar===================="); Calendar cal = Calendar.getInstance(); Date a1 = cal.getTime(); System.out.println("当前日期及时间:" + a1); int day = cal.get(Calendar.DATE); int month = cal.get(Calendar.MONTH) + 1; int year = cal.get(Calendar.YEAR); int hour = cal.get(Calendar.HOUR); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); System.out.println("Month:" + month); System.out.println("Day:" + day); System.out.println("year:" + year); System.out.println("WEEK_OF_YEAR:" + cal.get(cal.WEEK_OF_YEAR)); System.out.println("WEEK_OF_MONTH:" + cal.get(cal.WEEK_OF_MONTH)); System.out.println("DAY_OF_WEEK:" + cal.get(cal.DAY_OF_WEEK));// 从周日开始算 System.out.println("现在是" + year + "年" + month + "月" + day + "日"); System.out.println("现在是" + hour + "时" + minute + "分" + second + "秒"); } }