java程序猿经常会碰到的一个问题就是日期格式化。当接收参数中有日期或时间,那么就需要与前端商量好其格式,这边我知道是2种:1、时间戳 2、字符串。

先说一下时间戳,这个形势的参数,Java只需new Date(Long date)就能获得Date,但是我在使用过程中还是碰到奇怪的问题,就是时区与数据库对不上。获得的Date是CST格式的,而 CST却同时可以代表如下 4 个不同的时区:

Central Standard Time (USA) UT-6:00

Central Standard Time (Australia) UT+9:30

China Standard Time UT+8:00

Cuba Standard Time UT-4:00

所以用起来还是有点麻烦,于是我放弃了时间戳。

然后我用起了字符串,字符串就简单了,只需要用SimpleDateFormat格式化一下,而且后端在调试模式可以很明确看到什么时间。但是SimpleDateFormat有个缺点就是线程不安全,而且在使用的时候需要抛出异常或者try catch,至于为什么线程不安全我就不细说了,在阿里的Java开发手册(嵩山版)中有明确指出:【强制】SimpleDateFormat 是线程不安全的类,一般不要定义为 static变量,如果定义为 static, 必须加锁,或者使用 DateUtils工具类。 正例:注意线程安全,使用 DateUtils。亦推荐如下处理: private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; 说明:如果是JDK8 的应用,可以使用 Instant 代替 Date,LocalDateTime 代替 Calendar, DateTimeFormatter 代替SimpleDateFormat,官方给出的解释:simple beautiful strong immutable thread-safe。

那么解决他线程不安全有几种办法:

1、将SimpleDateFormat定义成局部变量,在每次用到的时候就创建一个对象,方法结束作为垃圾回收,但是这样会消耗内存,就是大家用一个杯子喝水,可能不卫生或者抢着喝,但是每人一个一次性杯子,就增加了开销。

2、加线程同步锁(synchronized)这个我忘的差不多了,自行百度,这不是本节重点。

3、使用ThreadLocal,这个同上。

4、这个简单,不安全咱不用,jdk1.8中新增了 LocalDate 与 LocalDateTime等类来解决日期处理方法,同时引入了一个新的类DateTimeFormatter来解决日期格式化问题。API中讲的很详细,重点是This class is immutable and thread-safe。这个类是不可变的和线程安全的。LocalDateTime,DateTimeFormatter两个类都是线程安全的,只要不创建为public类型就没啥问题。可以使用Instant代替 Date,LocalDateTime代替 Calendar,DateTimeFormatter 代替 SimpleDateFormat,具体使用方法可以查看API。

下面是我自用的一个工具类:

 1 package com.hmbb.demo.util;
2 import org.springframework.util.StringUtils;
3 import java.time.LocalDateTime;
4 import java.time.ZoneId;
5 import java.time.format.DateTimeFormatter;
6 import java.util.Date;
7 ​
8 /**
9 * @description 时间工具类
10 * @author: zx
11 * @create: 2020-10-28 09:43:30
12 **/
13 public class DateUtils {
14 ​
15 ​
16 private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
17 ​
18 /**
19 * 字符串转Date
20 * @param date 时间字符串 "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd"
21 * @param type null or "00" or "23"
22 * @return Date
23 */
24 public static Date getDate(String date,String type){
25 try {
26 if(StringUtils.isEmpty(date))return null;
27 if(date.length()==10){
28 date = date.concat(" 00:00:00");
29 }
30 LocalDateTime localDateTime = LocalDateTime.parse(date,formatter);
31 if(StringUtils.isEmpty(type)){
32 return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
33 }else{
34 return changeFormat(localDateTime,type);
35 }
36 }catch (Exception e){
37 e.printStackTrace();
38 }
39 return null;
40 }
41 private static Date changeFormat(LocalDateTime localDateTime,String type){
42 if("00".equals(type)){
43 localDateTime = localDateTime.withHour(00);
44 localDateTime = localDateTime.withMinute(00);
45 localDateTime = localDateTime.withSecond(00);
46 return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
47 }else if("23".equals(type)){
48 localDateTime = localDateTime.withHour(23);
49 localDateTime = localDateTime.withMinute(59);
50 localDateTime = localDateTime.withSecond(59);
51 return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
52 }else {
53 throw new IllegalArgumentException(type+"--type参数异常!");
54 }
55 }
56 }
注:type: null 返回原格式  00 当天最初时刻,时分秒为0  23 当天最后时刻,23时59分59秒

DateTimeFormatter接替SimpleDateFormat的更多相关文章

  1. 日期时间格式化 SimpleDateFormat与DateTimeFormatter

    原文:https://www.jianshu.com/p/b212afa16f1f 1.SimpleDateFormat为什么不是线程安全的? 如果我们把SimpleDateFormat定义成stat ...

  2. 还在使用SimpleDateFormat?你的项目崩没?

    如果是在多线程环境下,就需要注意了. 要点: 1.加Synchronized同步: 2.使用ThreadLocal: 3.jdk8使用DateTimeFormatter替代SimpleDateForm ...

  3. SimpleDateFormat 使用时出现的线程同步问题。。。

    错误使用: public static final SimpleDateFormat DAY_UI_MONTH_DAY_FORMAT = new SimpleDateFormat("MM-d ...

  4. SimpleDateFormat线程不安全原因及解决方案

    一. 线程不安全验证: /** * SimpleDateFormat线程安全测试 * 〈功能详细描述〉 * * @author 17090889 * @see [相关类/方法](可选) * @sinc ...

  5. 为什么SimpleDateFormat不是线程安全的?

    一.前言 日期的转换与格式化在项目中应该是比较常用的了,最近同事小刚出去面试实在是没想到被 SimpleDateFormat 给摆了一道... 面试官:项目中的日期转换怎么用的?SimpleDateF ...

  6. 阿里Java开发手册1.3.0 文字版

    版本: 1.3.0 update: 2017.9.25 一.编程规约 (一) 命名风格 1. [强制]代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符号结束. 反例:_name _na ...

  7. 304902阿里巴巴Java开发手册1.4.0

    转自官网 前言 <阿里巴巴Java开发手册>是阿里巴巴集团技术团队的集体智慧结晶和经验总结,经历了多次大规模一线实战的检验及不断完善,系统化地整理成册,回馈给广大开发者.现代软件行业的高速 ...

  8. 阿里巴巴 Java 开发手册 1.4.0

    一.编程规约(一) 命名风格1. [强制]代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符号结束.反例: _name / __name / $name / name_ / name$ ...

  9. Java开发最佳实践(一) ——《Java开发手册》之"编程规约"

    Java开发手册版本更新说明 专有名词解释 一. 编程规约 (一) 命名风格 (二) 常量定义 (三) 代码格式 (四) OOP 规约 (五) 集合处理 (六) 并发处理 (七) 控制语句 (八) 注 ...

随机推荐

  1. python数据结构实现(栈和链栈)

    栈 class Stack: def __init__(self, limit: int 10): self.stack = [] self.limit = limit def __bool__(se ...

  2. DOS批处理中%cd%与%~dp0的区别详解

    转载:https://www.jb51.net/article/105325.htm DOS批处理中%cd%与%~dp0的区别详解     Windows下批处理中%cd%和%~dp0都能用来表示当前 ...

  3. opencv 中从cv::line和resize()函数

    转自: https://blog.csdn.net/weixin_36340947/article/details/77095924 转自: https://blog.csdn.net/robinhj ...

  4. Unicode和多字节字符集

    今天自己写的发现一个输出路径程序使用unicode字符集只能输出单个的首字符,问了一下同事,改为使用多字节字符集,问题解决了 于是上网看了他们的区别:  很多没看完,但起码了解到字符集的演变过程, 转 ...

  5. P4821 [中山市选]生成树

    题目链接 我们可以看一下题目中给的这张图. 首先,树是没有环的,所以我们要把所有的环上的边都删去一条. 我们可以现在每个五边形上删去一条边. 但删完之后我们会发现,里面还有一圈. 这时候,我们就要在这 ...

  6. 【题解】[USACO09NOV]A Coin Game S

    Link \(\text{Solution:}\) 菜鸡自己想出来了状态设计,但是没有实现出来--菜死了 设\(dp[i][j]\)表示该选第\(i\)个,最多选\(j\)个的最优解.注意这里的定义仅 ...

  7. php数据显示在html截取字符

    <?php    echo mb_subsrt($s['content'],0,20,'gbkj')?> gbk也可以是utf8根据实际情况来

  8. mycat相关配置文件和参数解析

    #vi /usr/local/mycat/conf/schema.xml<!--######################################################### ...

  9. 初试Python

    01 Python简介 Python是一种跨平台的计算机程序设计语言.于1989年开发的语言,创始人范罗苏姆(Guido van Rossum),别称:龟叔(Guido). python具有非常多并且 ...

  10. js 无刷新文件上传 (兼容IE9 )

    之前项目中有个文件上传了需求,于是直接就使用了FormData对象异步上传,但是在测试得时候发现ie9无法正常上传(项目要求兼容IE9+),无奈,查资料得知IE9- 版本不支持formdata对象得异 ...