【hutool】使用问题

如何将Date转化为LocalDateTime

package cn.hutool.core.date;

public class LocalDateTimeUtil {
	/**
	 * {@link Date}转{@link LocalDateTime},使用默认时区
	 *
	 * @param date Date对象
	 * @return {@link LocalDateTime}
	 */
	public static LocalDateTime of(Date date) {
		if (null == date) {
			return null;
		}

		if (date instanceof DateTime) {
			return of(date.toInstant(), ((DateTime) date).getZoneId());
		}
		return of(date.toInstant());
	}
}

如何将LocalDateTime、LocalDate转化为Date

  • 方案1

对纯原生的转化方式Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant())进行简单封装。即先使用TemporalAccessorUtil#toInstant(TemporalAccessor)LocalDateTime转化为Instant(底层就是执行localDateTime.atZone(ZoneId.systemDefault()).toInstant()

package cn.hutool.core.date;

public class TemporalAccessorUtil extends TemporalUtil{
	/**
	 * {@link TemporalAccessor}转换为 {@link Instant}对象
	 *
	 * @param temporalAccessor Date对象
	 * @return {@link Instant}对象
	 * @since 5.3.10
	 */
	public static Instant toInstant(TemporalAccessor temporalAccessor) {
		if (null == temporalAccessor) {
			return null;
		}

		Instant result;
		if (temporalAccessor instanceof Instant) {
			result = (Instant) temporalAccessor;
		} else if (temporalAccessor instanceof LocalDateTime) {
			result = ((LocalDateTime) temporalAccessor).atZone(ZoneId.systemDefault()).toInstant();
		} else if (temporalAccessor instanceof ZonedDateTime) {
			result = ((ZonedDateTime) temporalAccessor).toInstant();
		} else if (temporalAccessor instanceof OffsetDateTime) {
			result = ((OffsetDateTime) temporalAccessor).toInstant();
		} else if (temporalAccessor instanceof LocalDate) {
			result = ((LocalDate) temporalAccessor).atStartOfDay(ZoneId.systemDefault()).toInstant();
		} else if (temporalAccessor instanceof LocalTime) {
			// 指定本地时间转换 为Instant,取当天日期
			result = ((LocalTime) temporalAccessor).atDate(LocalDate.now()).atZone(ZoneId.systemDefault()).toInstant();
		} else if (temporalAccessor instanceof OffsetTime) {
			// 指定本地时间转换 为Instant,取当天日期
			result = ((OffsetTime) temporalAccessor).atDate(LocalDate.now()).toInstant();
		} else {
			// issue#1891@Github
			// Instant.from不能完成日期转换
			//result = Instant.from(temporalAccessor);
			result = toInstant(LocalDateTimeUtil.of(temporalAccessor));
		}

		return result;
	}
}

再使用Date#from(Instant)

package java.util;

public class Date implements java.io.Serializable, Cloneable, Comparable<Date> {
	/**
     * Obtains an instance of {@code Date} from an {@code Instant} object.
     * <p>
     * {@code Instant} uses a precision of nanoseconds, whereas {@code Date}
     * uses a precision of milliseconds.  The conversion will truncate any
     * excess precision information as though the amount in nanoseconds was
     * subject to integer division by one million.
     * <p>
     * {@code Instant} can store points on the time-line further in the future
     * and further in the past than {@code Date}. In this scenario, this method
     * will throw an exception.
     *
     * @param instant  the instant to convert
     * @return a {@code Date} representing the same point on the time-line as
     *  the provided instant
     * @exception NullPointerException if {@code instant} is null.
     * @exception IllegalArgumentException if the instant is too large to
     *  represent as a {@code Date}
     * @since 1.8
     */
    public static Date from(Instant instant) {
        try {
            return new Date(instant.toEpochMilli());
        } catch (ArithmeticException ex) {
            throw new IllegalArgumentException(ex);
        }
    }
}
  • 方案2

DateTime类继承于java.util.Date类,为Date类扩展了众多简便方法,这些方法多是DateUtil静态方法的对象表现形式,使用DateTime对象可以完全替代开发中Date对象的使用。

package cn.hutool.core.date;

public class DateUtil extends CalendarUtil {
	/**
	 * {@link TemporalAccessor}类型时间转为{@link DateTime}<br>
	 * 始终根据已有{@link TemporalAccessor} 产生新的{@link DateTime}对象
	 *
	 * @param temporalAccessor {@link TemporalAccessor},常用子类: {@link LocalDateTime}、 LocalDate
	 * @return 时间对象
	 * @since 5.0.0
	 */
	public static DateTime date(TemporalAccessor temporalAccessor) {
		return new DateTime(temporalAccessor);
	}
}
  • 示例
public class Test {
	public static void main(String[] args) {
        final LocalDateTime localDateTime = LocalDateTime.of(2022, 5, 9, 11, 36);
        final Date date1 = Date.from(TemporalAccessorUtil.toInstant(localDateTime));
        final DateTime date2 = DateUtil.date(localDateTime);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Hutool工具库来导出Excel文件。下面是一个简单的示例代码: ```java import cn.hutool.core.date.DateUtil; import cn.hutool.poi.excel.ExcelUtil; import cn.hutool.poi.excel.ExcelWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ExcelExportExample { public static void main(String[] args) { // 创建ExcelWriter对象 ExcelWriter writer = ExcelUtil.getWriter("D:/example.xlsx"); // 设置表头 writer.addHeaderAlias("id", "ID"); writer.addHeaderAlias("name", "姓名"); writer.addHeaderAlias("age", "年龄"); writer.addHeaderAlias("birthday", "生日"); // 设置内容 List<Person> personList = createTestData(); writer.write(personList, true); // 关闭writer,完成写入 writer.close(); } // 创建测试数据 private static List<Person> createTestData() { List<Person> personList = new ArrayList<>(); personList.add(new Person(1, "张三", 20, DateUtil.parse("2000-01-01"))); personList.add(new Person(2, "李四", 22, DateUtil.parse("1998-05-10"))); personList.add(new Person(3, "王五", 25, DateUtil.parse("1995-12-20"))); return personList; } // 定义Person类 static class Person { private Integer id; private String name; private Integer age; private Date birthday; // 省略构造方法、getter和setter } } ``` 上述代码通过Hutool的ExcelWriter类来创建一个ExcelWriter对象,并指定要导出的文件路径。然后,使用addHeaderAlias方法设置表头别名,以及write方法将数据写入Excel文件中。最后,调用close方法关闭writer对象,完成写入操作。 请注意,需要先在项目中引入Hutool的依赖,例如: ```xml <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.3.10</version> </dependency> ``` 这样就可以使用Hutool来导出Excel文件了。希望对你有所帮助!如有任何问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值