时间戳、日期格式、以及相互转换

来源:互联网 发布:大连银行网络大学 编辑:程序博客网 时间:2024/05/24 01:51

获取当前时间

    public static void main(String[] args) throws Exception {        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");        String Today = format.format(new Date());        System.out.println(Today);    }

时间格式可以自定义

SimpleDateFormat(“yyyyMMdd”)的格式是通过自己定义的,例:
yyyyMMdd
dd/mm/yyyy
yyyy-MM-dd HH:mm:ss

Java日期格式化中字母大小写的区别

YYYY 代表 Week Year(周年)
yyyy 代表year
MM 代表 月(Month)
mm代表 秒(Min)
HH代表24小时制 //HH 08 //H 8
hh代表12小时制

获取当前时间戳

    public static void main(String[] args) throws Exception {        long t = System.currentTimeMillis();        System.out.println(t);    }

时间戳转换成当前时间

    public static void main(String[] args) throws Exception {        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd : hh:mm:ss");        long t = System.currentTimeMillis();        String d = format.format(t);        Date date = format.parse(d);        System.out.println("Format To String(Date):" + d);        System.out.println("Format To Date:" + date);    }

当前时间转换成时间戳

    public static void main(String[] args) throws Exception {        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        String time = format.format(new Date());        Date date2 = format.parse(time);        System.out.print("Format To times:" + date2.getTime());    }

注意:

创建SimpleDateFormat实例时,new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);里面字符串头尾不要有空格,不然获取到的时间前后因为会有空格的

字符串转成时间戳时要先定义一个long类型的变量。Java获取的时间戳精确到毫秒。除以1000精确到秒