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. 靠这些秋招秘笈,齐姐的学妹今年已经拿到了 8 个offer!

    小齐说: 现在秋招进行时,正在找工作的小伙伴进度都怎么样了呀? 今天这篇文章是我武大的学妹今年秋招的经验分享,庆妹去年才决定转行,现在已手握 N+ 个 offer - 这篇文章干货满满,庆妹对每一块面 ...

  2. if else与switch for与foreach

    if...else...适用于变量判断 switch适用于常量判断(switch只判断一次,if else 判断多次) foreach只适用于集合和数组查询(foreach不支持增加删除操作) for ...

  3. Linux下安装ZooKeeper-3.5.6

    下载 官网下载地址是https://www.apache.org/dyn/closer.cgi/zookeeper,下载apache-zookeeper-3.5.6-bin.tar.gz.   sta ...

  4. 报表工具FastReport VCL 最新版发布!

    新功能 为主要包类添加了类引用 在报表设计器中添加了SQL编辑器的自定义 为TfrxReport的操作添加了延迟的命令池:PrepareReport,ShowReport,LoadFrom.可以调用R ...

  5. 从零搭建Golang开发环境--go修仙序章

    1. 什么是go语言 Go(又称 Golang)是 Google 的 Robert Griesemer,Rob Pike 及 Ken Thompson 开发的一种静态 .强类型.编译型语言 .Go 语 ...

  6. ByPass Mode(略过模式或旁路模式)

    参考: 1. https://baike.baidu.com/item/%E6%97%81%E8%B7%AF%E6%A8%A1%E5%BC%8F/3120563 2. https://zhidao.b ...

  7. [学习笔记] 数位DP的dfs写法

    跟着洛谷日报走,算法习题全都有! 嗯,没错,这次我也是看了洛谷日报的第84期才学会这种算法的,也感谢Mathison大佬,素不相识,却写了一长篇文章来帮助我学习这个算法. 算法思路: 感觉dfs版的数 ...

  8. SpringBoot 优化

  9. Linux 下 svn 场景实例及常用命令详解

    一.SVN使用场景实例 问题: 在使用svn做为版本控制系统的软件开发中,经常会有这样的需求:在工作复本目录树的不同目录中增加了很多文件,但未纳入版本控制系统,这时如果使用svn add命令一个一个的 ...

  10. OAuth 2.0 Server PHP实现示例

    需求实现三方OAuth2.0授权登录 使用OAuth服务OAuth 2.0 Server PHP 环境nginx mysqlphp 框架Yii 一 安装 项目目录下安装应用 composer.phar ...