时间

核心的类:java.util.Date,当前的计算机时间、

点击查看代码
public static void main(String[] args) {
        Date d =new Date();
        System.out.println(d);//获取UTF时间格式
        long time =d.getTime();////1970-01-01 0:0:0 到当前时间的毫秒数
        System.out.println(time);
    }
![image](https://img2023.cnblogs.com/blog/2326800/202303/2326800-20230318093540735-1922514546.png)

# 时间运算
点击查看代码
  public static void main(String[] args) {
        long nowtime =new Date().getTime();
        long lasttime =1000L * 60 * 60 * 24 * 365 * 10;
        long oldTime = nowtime - lasttime;//10年前的毫秒计时
        Date d2 = new Date(oldTime);//从毫秒计时变为时间对象
        System.out.println(d2);
    }
![image](https://img2023.cnblogs.com/blog/2326800/202303/2326800-20230318093644066-1142368661.png)

# 获取时间单位
点击查看代码
public static void main(String[] args) {
        Calendar c =Calendar.getInstance();
        c.setTime(new Date(0));
        System.out.println(c.get(Calendar.YEAR));
        System.out.println(c.get(Calendar.MONTH)+1);
        System.out.println(c.get(Calendar.DAY_OF_MONTH));
        System.out.println(c.get(Calendar.HOUR));//根据时区变化
        System.out.println(c.get(Calendar.MINUTE));
        System.out.println(c.get(Calendar.SECOND));
        System.out.println(c.get(Calendar.MILLISECOND));

    }
![image](https://img2023.cnblogs.com/blog/2326800/202303/2326800-20230318093742616-802135209.png)

# 时间格式化:SimpleDateFormat ![image](https://img2023.cnblogs.com/blog/2326800/202303/2326800-20230318094519382-556708929.png)
点击查看代码
 public static void main(String[] args) throws ParseException {
        SimpleDateFormat s =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeStr ="2011-11-11 11:11:11";
        Date date =s.parse(timeStr);
        System.out.println(date);
        String newStrTime =s.format(date);
        System.out.println(newStrTime);
    }
![image](https://img2023.cnblogs.com/blog/2326800/202303/2326800-20230318093916737-826570017.png)

posted @ 2023-03-18 09:39  卡卡罗特kk  阅读(35)  评论(0)    收藏  举报