Java 时间的使用
1. 获取当前时间戳
方法一:System.currentTimeMillis(); (13位时间戳,long类型)
方法二:new Date().getTime(); (13位时间戳,long类型)
方法三:Calendar.getInstance().getTimeInMillis(); (13位时间戳,long类型)
2. 获取当前/指定时间(Date类型)
Date date = new Date(); //Tue Oct 13 10:47:06 CST 2020 System.out.println(new Date(1000L)); //Thu Jan 01 08:00:01 CST 1970
3. 将日期时间转换为指定格式
public static void demo01() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String text = sdf.format(date); System.out.println(text); // 2020-10-13 10:49:35 System.out.println(date); // Tue Oct 13 10:49:35 CST 2020 }
4. 将指定格式日期字符串转化为Date格式
public static void demo02() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String text = "2020-10-01 07:10:00"; Date date = sdf.parse(text); System.out.println(date); // Thu Oct 01 07:10:00 CST 2020 }
5. 获取指定日历字段中的某个值
private static void demo01() { Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); System.out.println(year); //2020 }
6. 将日历字段设置为指定值
private static void demo02() { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, 2009); int year = c.get(Calendar.YEAR); System.out.println(year); // 2009 c.set(2009, 9, 9); int month = c.get(Calendar.MONTH); System.out.println(month); //9 }
7. 将日历指定字段增加或减少
private static void demo03() { Calendar c = Calendar.getInstance(); System.out.println(c.get(Calendar.YEAR)); //2020 c.add(Calendar.YEAR, -2); System.out.println(c.get(Calendar.YEAR)); //2018 }
8. 把日历对象转化为日期对象
private static void demo04() { Calendar c = Calendar.getInstance(); Date date = c.getTime(); System.out.println(date); //Tue Oct 13 11:32:33 CST 2020 }
猪猪侠要努力呀!