java Date

一、Date

1、注意是util包

2、作用

与时间相关的类

3、语法

Date date = new Date();
// 获取当前的时间 Mon Feb 10 14:19:51 CST 2020
System.out.println(date);
// 获取毫秒 1581315591562
long time = date.getTime();
System.out.println(time);

二、SimpleDateFormat

1、作用:使日期格式化

2、规则

y  年

M  月

d  日

H  时

m  分

s   秒

ps:(吐槽)与linux的时间格式不一样

3、语法

a、format

作用:Date对象->时间格式

初始化SimpleDateFormat对象,并确定时间的格式(通过构造方法)

将时间转换成自定义的格式

package cn.wt.day12;


import java.text.SimpleDateFormat;
import java.util.Date;

public class Demon01 {
    public static void main(String[] args) {
        demon01();
    }

    private static void demon01() {
        Date date = new Date();
        // 获取当前的时间 Mon Feb 10 14:19:51 CST 2020
        System.out.println(date);
        // 获取毫秒 1581315591562
        long time = date.getTime();
        System.out.println(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sdfFormat = sdf.format(date);
        System.out.println(sdfFormat);
    }
}

b、parse

作用:将格式化的时间解析Date对象

过程:

初始化SimpleDateFormat对象,并确认时间的格式(通过构造方法)

将符合时间格式的字符串,转换成Date对象

注意:异常的抛出throws

package cn.wt.day12;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Demon01 {
    public static void main(String[] args) throws ParseException {
        demon01();
        demon02();
    }

    private static void demon02() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dp = sdf.parse("2020-02-10 14:31:28");
        System.out.println(dp);     // Mon Feb 10 14:31:28 CST 2020
    }

    private static void demon01() {
        Date date = new Date();
        // 获取当前的时间 Mon Feb 10 14:19:51 CST 2020
        System.out.println(date);
        // 获取毫秒 1581315591562
        long time = date.getTime();
        System.out.println(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sdfFormat = sdf.format(date);
        System.out.println(sdfFormat);
    }
}

 

posted @ 2020-02-10 14:40  市丸银  阅读(150)  评论(0编辑  收藏  举报