Java中Date日期以及日期格式化

您所在的位置:网站首页 31982大写 Java中Date日期以及日期格式化

Java中Date日期以及日期格式化

2023-09-12 01:51| 来源: 网络整理| 查看: 265

获取当前日期

Date date = new Date();

程序如下:

import java.util.Date; public class Test { public static void main(String[] args) { Date date = new Date(); System.out.println(date); } }

 运行结果

 获取指定距离1970年1月1日8点的日期,为什么是8点呢,不应该是0点吗,因为我们这里是北京时区,与格林威治时间差8个小时,所以是8点

Date date = new Date(1000);

import java.util.Date; public class Test { public static void main(String[] args) { Date date = new Date(1000); //这里是毫秒值 System.out.println(date); } }

 

是不是看着这个日期的格式有点不舒服,我也是这种感觉,来格式化一波,格式化用的是SimpleDateFormat类,首先声明一个格式化对象

SimpleDateFormat simpleDateFormat = new SimpleDateFormat();

simpleDateFormat.format(date);

import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) { Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); System.out.println(simpleDateFormat.format(date)); } }

上面是SimpleDateFormat的默认格式化格式,我们也可以指定格式化格式,这里月的M要大写,因为跟分离的m冲突了,毕竟月比分大嘛,所以让月大写分小写了,大写的HH,意思是24时格式。

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

simpleDateFormat.format(date);

import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) { Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(simpleDateFormat.format(date)); } }

 

这是不是看着就舒服多了,还不止,还能自定义呢

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

simpleDateFormat.format(date);

import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) { Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(simpleDateFormat.format(date)); } }

 

好了,其他的就不再多演示了,接下来就来字符串转日期吧,这里需要注意一下有异常要处理,因为有些字符串根本就转化不了日期

String str = "2019/11/25 11:20";

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");

Date date = simpleDateFormat.parse(str);

import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) { String str = "2019/11/25 11:20"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); try { Date date = simpleDateFormat.parse(str); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); } } }

 

好了,这样一来,字符串也能转化为日期了,如果看着这个格式不舒服,那就可以用上面的日期格式化了 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3