前言
如何采用Java的jdk1.8的API来实现,对于Instant格式化为字符串呢?
相信很多人可能都不是很清晰,我们就来聊一下这个话题。
问题复现
当在如下的场景时
Instant instant = ...;
String out = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(instant);
想要通过使用Jdk1.8的时间Api来进行格式化Instant到字符串,该怎么实现呢??
苦尽脑汁想出来的上述代码实现,发现报了异常
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
at java.time.Instant.getLong(Instant.java:608)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
...
那么,正确的靠谱的,实现方案是怎么样的呢,我们就来看一下这些情况。
问题解决
为了格式化Instant一个问题是需要了解的,那就是time zone。
没有时区,将无法进行格式化到人类的时间定义。
时区可以通过以下代码,被添加到格式器上去
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
.withLocale( Locale.UK )
.withZone( ZoneId.systemDefault() );
如果有针对性特殊要求,想要使用ISO-8601 进行格式化编码,则需要修改下上述代码
DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))
完事就是格式化成字符串
Instant instant = Instant.now();
String output = formatter.format( instant );
System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and
Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );
运行结果为:
formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34
总结
格式化并不难,难得是熟练运行相关的API。
⭐本专栏旨在对JAVA的基础语法及知识点进行全面且详细的讲解,完成从0到1的java学习,面向零基础及入门的学习者,通过专栏的学习可以熟练掌握JAVA编程,同时为后续的框架学习,进阶开发的代码能力打下坚实的基础。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
二. 创建一个 job 并继承 QuartzJobBean
@Slf4j
public class HelloWorldJob extends QuartzJobBean {
@Override
protected void executeInternal(Jo
本期4ye又带来一个奇怪的Bug啦,是关于 jdk8 中 lambdas 推导泛型失败而导致的编译期错误,下面让我们一起来看看叭 😝
Error:(24, 29) java: 未报告的异常错误java.lang.Throwable; 必须对其进行捕获或声明以便抛出
下面让我们一起来看看叭
import java.util.Optional;
public class B {
public static void main(String[] args) {
String s=null;
Optional.ofNullable(s)
bug描述
上次使用jackson进行数据转换的时候发生了下面这个错误。
java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class com.example.demo.model.User (java.util.LinkedHashMap is in module java.base of loader 'bo
实现单例模式的八种模式:饿汉式,懒汉式,双重检查锁模式,静态内部类模式,序列化模式,注册式之枚举,注册式之容器,线程实现ThreadLocal
参考大神Tom的《Spring 5核心原理与30个类手写实战-谭勇德》
单例模式 Singleton Pattern
确保一个类在任何场景下只有一个实例,并提供一个全局访问点
J2EE 标准中的 ServletContext 、 Spring 框架应用中的ApplicationContext 、数据库的连接池 也都是单例形式
在类加载的时候就立即初始化,并且创建单例对象,属于线程安全
SpringIOC容器Applic