Java8的DateTimeFormatter与SimpleDateFormat的区别详解

两者最大的区别是,Java8的DateTimeFormatter是线程安全的,而SimpleDateFormat并不是线程安全。

package com.main;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Main {

  public static void main(String args[]){

    //解析日期
    String dateStr= "2016年10月25日";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
    LocalDate date= LocalDate.parse(dateStr, formatter);

    //日期转换为字符串
    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm a");
    String nowStr = now .format(format);
    System.out.println(nowStr);

    //ThreadLocal来限制SimpleDateFormat
    System.out.println(format(new Date()));
  }

  //要在高并发环境下能有比较好的体验,可以使用ThreadLocal来限制SimpleDateFormat只能在线程内共享,这样就避免了多线程导致的线程安全问题。
  private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
    @Override
    protected DateFormat initialValue() {
      return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
  };

  public static String format(Date date) {
    return threadLocal.get().format(date);
  }
}

Java8 (LocalDateTime) 时间转换

注意:LocalDateTime是带时分秒的

1.将LocalDateTime转为自定义的时间格式的字符串

public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
  return localDateTime.format(formatter);
}

2.将long类型的timestamp转为LocalDateTime

public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
  Instant instant = Instant.ofEpochMilli(timestamp);
  ZoneId zone = ZoneId.systemDefault();
  return LocalDateTime.ofInstant(instant, zone);
}

3.将LocalDateTime转为long类型的timestamp

public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
  ZoneId zone = ZoneId.systemDefault();
  Instant instant = localDateTime.atZone(zone).toInstant();
  return instant.toEpochMilli();
}

4.将某时间字符串转为自定义时间格式的LocalDateTime

public static LocalDateTime parseStringToDateTime(String time, String format) {
  DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
  return LocalDateTime.parse(time, df);
}

到此这篇关于Java8的DateTimeFormatter与SimpleDateFormat的区别详解的文章就介绍到这了,更多相关Java8 DateTimeFormatter与SimpleDateFormat内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Java中SimpleDateFormat用法详解

    public class SimpleDateFormat extends DateFormat SimpleDateFormat 是一个以国别敏感的方式格式化和分析数据的具体类. 它允许格式化 (date -> text).语法分析 (text -> date)和标准化. SimpleDateFormat 允许以为日期-时间格式化选择任何用户指定的方式启动. 但是,希望用 DateFormat 中的 getTimeInstance. getDateInstance 或 getDateTime

  • Java中的SimpleDateFormat使用详解

    public class SimpleDateFormat extends DateFormat SimpleDateFormat 是一个以国别敏感的方式格式化和分析数据的具体类. 它允许格式化 (date -> text).语法分析 (text -> date)和标准化. SimpleDateFormat 允许以为日期-时间格式化选择任何用户指定的方式启动. 但是,希望用 DateFormat 中的 getTimeInstance. getDateInstance 或 getDateTime

  • Java使用DateTimeFormatter格式化输入的日期时间

    要求: 用DateTimeFormatter实现: 用扫描器获取输入的时间(年月日时分),这个时间的格式是常用的格式,然后格式化这个时间,把格式化的时间输出到控制台,可以在控制台重复输入时间.格式化的时间参考企业微信聊天记录的展示时间 分析: 1.时间的常用格式为: xxxx-xx-xx xx:xx xxxx/xx/xx xx:xx xxxx.xx.xx xx:xx 等格式 2.微信显式时间格式为: 今天显式: 00:01 - 23:59 ; 昨天显式: 昨天 01:01 ; 前天显式: 周几

  • Java多线程环境下SimpleDateFormat类安全转换

    一.SimpleDateFormat类 package state; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * SimpleDateFormat类负责日期的转换与格式化 * 解决SimpleDateFormat类多线程环境下转换错误问题 * @author zc * */ public class SimpleDateFormatThread e

  • JAVA使用SimpleDateFormat类表示时间代码实例

    在程序开发中,经常需要处理日期和时间的相关数据,此时我们可以使用 java.util 包中的 Date 类.这个类最主要的作用就是获取当前时间,我们来看下 Date 类的使用: 使用 Date 类的默认无参构造方法创建出的对象就代表当前时间,我们可以直接输出 Date 对象显示当前的时间,显示的结果如下: 其中, Wed 代表 Wednesday (星期三), Jun 代表 June (六月), 11 代表 11 号, CST 代表 China Standard Time (中国标准时间,也就是

  • 简单了解JAVA SimpleDateFormat yyyy和YYYY的区别

    最近有一个功能是对输入的日期格式化,设计给出的范例是 YYYY-MM-dd HH:mm:ss,于是我简单验证了一下是可以的,然后就这么在手册里写了.然后偶然发现有地方也用yyyy啊,这个到底有神马区别啊,还是随便用呢.看了下jdk,这么说的: 也就是说Y表示的是Week year,可是,这个Week year又是什么..jdk文档贴心地给出了Examples,然而并没有什么卵用.. 经过试验,得出的结果如下:Week year意思是当天所在的周属于的年份,一周从周日开始,周六结束,只要本周跨年,

  • Java SimpleDateFormat线程安全问题原理详解

    今天百度一些资料偶然发现SimpleDateFormat居然不是线程安全的,平时使用时根本没有考虑,万幸今天发现了这个问题,得把写的代码得翻出来整理一下了. 一般我们使用的SimpleDateFormat一般是这样写的: public void method() { ... DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = dateFormat.parse("202

  • Java使用DateTimeFormatter实现格式化时间

    用扫描器获取输入的时间(年月日时分),这个时间的格式是常用的格式,然后格式化这个时间,把格式化的时间输出到控制台,可以在控制台重复输入时间.格式化的时间参考企业微信聊天记录的展示时间.用DateTimeFormatter实现,功能如下: 同年: 不同年: 同月:月日+上午/下午+时分 同年不同月:月日+时分 今天:上午/下午+时分 明天:明天+上午/下午+时分 昨天:昨天+上午/下午+时分 包括今天在内的一周内:星期+上午/下午+时分 首先看一下测试类: package hrkj; import

  • Java8的DateTimeFormatter与SimpleDateFormat的区别详解

    两者最大的区别是,Java8的DateTimeFormatter是线程安全的,而SimpleDateFormat并不是线程安全. package com.main; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter;

  • Java8中AbstractExecutorService与FutureTask源码详解

    目录 前言 一.AbstractExecutorService 1.定义 2.submit 3.invokeAll 4.invokeAny 二.FutureTask 1.定义 2.构造方法 3.get 4.run/ runAndReset 5. cancel 三.ExecutorCompletionService 1.定义 2.submit 3.take/ poll 总结 前言 本篇博客重点讲解ThreadPoolExecutor的三个基础设施类AbstractExecutorService.F

  • JS处理数据四舍五入(tofixed与round的区别详解)

    1 .tofixed方法 toFixed() 方法可把 Number 四舍五入为指定小数位数的数字.例如将数据Num保留2位小数,则表示为:toFixed(Num):但是其四舍五入的规则与数学中的规则不同,使用的是银行家舍入规则,银行家舍入:所谓银行家舍入法,其实质是一种四舍六入五取偶(又称四舍六入五留双)法.具体规则如下: 简单来说就是:四舍六入五考虑,五后非零就进一,五后为零看奇偶,五前为偶应舍去,五前为奇要进一. 显然这种规则不符合我们平常在数据中处理的方式.为了解决这样的问题,可以自定义

  • AngularJS constant和value区别详解

    angularJS可以通过constant(name,value)和value(name,value)对于创建服务也是很重要的. 相同点是:都可以接受两个参数,name和value. 区别: 1.constant(name,value)可以将一个已经存在的变量值注册为服务,并将其注入到应用的其他部分中.其中,name为注册的常量的名字,value为注册的常量的值或对象. 举例: (1)value为值时: angular.module('myApp') .constant('apiKey','12

  • 基于python中staticmethod和classmethod的区别(详解)

    例子 class A(object): def foo(self,x): print "executing foo(%s,%s)"%(self,x) @classmethod def class_foo(cls,x): print "executing class_foo(%s,%s)"%(cls,x) @staticmethod def static_foo(x): print "executing static_foo(%s)"%x a=A(

  • Oracle10个分区和Mysql分区区别详解

    Oracle10g分区常用的是:range(范围分区).list(列表分区).hash(哈希分区).range-hash(范围-哈希分区).range-list(列表-复合分区). Range分区:Range分区是应用范围比较广的表分区方式,它是以列的值的范围来做为分区的划分条件,将记录存放到列值所在的range分区中. 如按照时间划分,2010年1月的数据放到a分区,2月的数据放到b分区,在创建的时候,需要指定基于的列,以及分区的范围值. 在按时间分区时,如果某些记录暂无法预测范围,可以创建m

  • 基于DOM节点删除之empty和remove的区别(详解)

    要移除页面上节点是开发者常见的操作,jQuery提供了几种不同的方法用来处理这个问题,这里我们开仔细了解下empty和remove方法 empty 顾名思义,清空方法,但是与删除又有点不一样,因为它只移除了 指定元素中的所有子节点. 这个方法不仅移除子元素(和其他后代元素),同样移除元素里的文本.因为,根据说明,元素里任何文本字符串都被看做是该元素的子节点.请看下面的HTML: <div class="hello"><p>这是p标签</p></

  • node.js中grunt和gulp的区别详解

    node.js中grunt和gulp的区别详解 自nodeJS登上前端舞台,自动化构建变得越来越流行.目前最流行的当属grunt和gulp,这两个光看名字挺像,功能也差不多,不过gulp能在grunt这位大哥如日中天的境况下开辟出自己的一片天地,有着她独到的优点. 易用 Gulp相比Grunt更简洁,而且遵循代码优于配置策略,维护Gulp更像是写代码. 高效 Gulp相比Grunt更有设计感,核心设计基于Unix流的概念,通过管道连接,不需要写中间文件. 高质量 Gulp的每个插件只完成一个功能

  • 基于js中this和event 的区别(详解)

    今天在看javascript入门经典-事件一章中看到了 this 和 event 两种传参形式.因为作为一个初级的前端开发人员平时只用过 this传参,so很想弄清楚,this和event的区别是什么,什么情况下用什么比较合适. onclick = changeImg(this)       vs     onclick = changeImg(event) <img src='usa.gif' onclick="changeImg(event)" /> <scrip

  • python dict.get()和dict['key']的区别详解

    先看代码: In [1]: a = {'name': 'wang'} In [2]: a.get('age') In [3]: a['age'] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-3-a620cb7b172a> in <module>() ----&g

随机推荐