【java】mapperstruct将date转string

import com.entity.WindowEntity;
import com.vo.WindowVO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;
import org.springframework.stereotype.Component;

import java.util.List;

@Mapper(uses = {WindowConverter.WindowConverterWorker.class})
public interface WindowConverter {
    WindowConverter INSTANCE = Mappers.getMapper(WindowConverter.class);

    @Mapping(target = "createTime", source = "createTime", dateFormat = "yyyy-MM-dd HH:mm:ss")
    WindowVO entityToVO(WindowEntity windowEntity);

    List<WindowVO> entityListTOVOList(List<WindowEntity> list);

    @Component
    @Named("WindowConverterWorker")
    class WindowConverterWorker{

    }
}


Java 中将 `Date` 对象换成字符串是一个常见的操作。你可以通过多种方式进行这种类型的换,以下是几种常用的方法: ### 使用 SimpleDateFormat 这是最传统的日期格式化方法之一。 ```java import java.text.SimpleDateFormat; import java.util.Date; public class DateToStringExample { public static void main(String[] args) { // 创建一个新的Date对象,默认为当前时间 Date currentDate = new Date(); // 定义日期的显示格式 String dateFormatPattern = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(dateFormatPattern); try { // 将Date对象换为指定格式的String对象 String formattedDate = sdf.format(currentDate); System.out.println("Formatted date is: " + formattedDate); } catch (Exception e) { // 捕获异常并打印堆栈跟踪信息 e.printStackTrace(); } } } ``` ### 使用 DateTimeFormatter (推荐) 从 Java 8 开始引入了新的日期时间和格式API (`java.time` 包),它更易用、线程安全,并提供了更多的功能。对于新项目来说,强烈建议使用这个库来进行日期处理。 ```java import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class NewDateTimeApiExample { public static void main(String[] args){ LocalDateTime localDateTime = LocalDateTime.now(); // 格式化模式定义 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); // 换LocalDateTime到字符串 String formattedDateStr = localDateTime.format(formatter); System.out.println(formattedDateStr); } } ``` 如果你需要将旧版的 `java.util.Date` 类型的数据化为新版的时间类型数据以便利用上述的新特性,则可以这样做: ```java Instant instant = currentUtilDate.toInstant(); ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault()); LocalDateTime ldt = zdt.toLocalDateTime(); ``` 以上就是一些基本的方式用于把Java中的日期成字符串。希望这能帮助您解决问题!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王佑辉

老板,赏点吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值