LocalDateTime格式化

说明

Jackson

依赖

默认引入spring-boot-starter-web,即自动引入Jackson;

配置ObjectMapper


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * jackson配置
 *
 * @author liaorj
 * @date 2024/03/21
 */
@Configuration
public class JacksonConfig {

    /**
     * jackson配置ObjectMapper对LocalDateTime的序列化、反序列化
     *
     * @return
     */
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        // other serializer and deSerializer config ...

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

    /*@Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> {
            jacksonObjectMapperBuilder.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            jacksonObjectMapperBuilder.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

            jacksonObjectMapperBuilder.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
            jacksonObjectMapperBuilder.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

            jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        };
    }*/
}

 使用ObjectMapper

从spring容器中注入,才能生效,直接new的话本人试过,会报错。

    @Resource
    private ObjectMapper objectMapper;

使用@JsonFormat

  • 直接使用该注解,不依赖上述配置;
  • get出参、post出参和入参使用;
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private LocalDate date;

    @JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+8")
    private LocalTime startTime;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime createTime;

使用@DateTimeFormat

  • 直接使用该注解,不依赖上述配置;
  • get入参使用;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate date;

 配置RabbitMQ消息转换器

  • 依赖上述ObjectMapper配置,否则格式化LocalDateTime字段异常;
  • 在注册RabbitMQ消息转换器时,需传入ObjectMapper对象;
  • 代码中的自动创建消息id设置,与本主题无关;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * rabbitmq配置
 *
 * @author liaorj
 * @date 2024/02/26
 */
@Configuration
public class RabbitMQConfig {

    /**
     * AMQP消息转换器,
     * 原本是jdk序列化的,由于消息空间占用较大,且不友好,所以配置该转换器。
     * 发送端和消费端都配置。
     * @return
     */
    @Bean
    public MessageConverter messageConverter(ObjectMapper objectMapper) {
        //定义消息转换器
        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(objectMapper);
        //配置自动创建消息id,用于识别不同消息,也可以在业务中基于id判断消息是否重复
        converter.setCreateMessageIds(true);
        return converter;
    }

}

可能遇到的异常 

以上没设置好,可能遇到的异常:

1、LocalDateTime格式化异常:

`java.time.LocalDate` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"

2、RabbitMQ消息转换异常:

MessageConversionException: Failed to convert Message content]

FastJson

待续...

  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 在Java中,可以使用LocalDateTime类将时间格式化为所需的格式。以下是将LocalDateTime格式化为不同格式的示例代码: 1. 将LocalDateTime格式化为yyyy-MM-dd HH:mm:ss格式: ``` LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDateTime = now.format(formatter); System.out.println(formattedDateTime); ``` 输出: ``` 2023-03-03 12:34:56 ``` 2. 将LocalDateTime格式化为yyyy/MM/dd HH:mm:ss格式: ``` LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); String formattedDateTime = now.format(formatter); System.out.println(formattedDateTime); ``` 输出: ``` 2023/03/03 12:34:56 ``` 3. 将LocalDateTime格式化为yyyy年MM月dd日 HH时mm分ss秒格式: ``` LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒"); String formattedDateTime = now.format(formatter); System.out.println(formattedDateTime); ``` 输出: ``` 2023年03月03日 12时34分56秒 ``` 你可以根据需要修改格式化字符串来得到你想要的格式。 ### 回答2: 在Java中,可以使用LocalDateTime类进行时间格式化。 我们可以通过DateTimeFormatter类来定义想要的日期时间格式。创建DateTimeFormatter对象时,可以使用ofPattern方法来指定日期时间格式的模式。例如,要将LocalDateTime对象格式化为"yyyy-MM-dd HH:mm:ss"的字符串,可以使用如下代码: DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); String formattedDateTime = now.format(formatter); 上述代码中,使用ofPattern方法指定了日期时间的格式模式"yyyy-MM-dd HH:mm:ss",并将当前时间通过LocalDateTime.now()方法获取到的LocalDateTime对象进行格式化。format方法将LocalDateTime对象转换为指定格式的字符串,并将结果赋值给formattedDateTime变量。 另外,还可以使用DateTimeFormatter类的parse方法将字符串转换为LocalDateTime对象。例如,要将字符串"2022-01-01 12:00:00"转换为LocalDateTime对象,可以使用如下代码: String dateTimeString = "2022-01-01 12:00:00"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter); 上述代码中,使用ofPattern方法指定了日期时间的格式模式"yyyy-MM-dd HH:mm:ss",并使用parse方法将字符串"2022-01-01 12:00:00"转换为LocalDateTime对象。 通过使用DateTimeFormatter类,我们可以方便地对LocalDateTime对象进行格式化和解析,使其在不同的时间格式之间进行转换。 ### 回答3: 在Java中,可以使用LocalDateTime类对时间进行格式化LocalDateTime类是Java 8中引入的日期时间类,它可以表示不带时区的日期和时间。 要对LocalDateTime进行格式化,可以使用DateTimeFormatter类。DateTimeFormatter类是一个帮助类,可以用于定义时间的格式。 以下是一个简单的例子,演示如何将LocalDateTime对象格式化为指定的字符串格式: ```java import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LocalDateTimeFormattingExample { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDateTime = now.format(formatter); System.out.println("Formatted DateTime: " + formattedDateTime); } } ``` 在上面的例子中,首先我们获取了当前的LocalDateTime对象,然后创建了一个DateTimeFormatter对象,并指定了希望的日期时间格式,如"yyyy-MM-dd HH:mm:ss"。 然后,我们使用format方法将LocalDateTime对象转换为指定格式的字符串,并将其打印出来。 你可以根据自己的需求定义不同的格式,例如"yyyy年MM月dd日 HH:mm:ss"等。 需要注意的是,DateTimeFormatter是线程安全的,所以可以在多线程环境下共享使用。 希望以上例子能够帮助你了解如何在Java中使用LocalDateTime对时间进行格式化

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值