时间类型与字符串之间的互转

LocalDateTime类型转换成String类型

// 获取当前时间
LocalDateTime localDateTime = LocalDateTime.now();
// 将没有格式化的当前时间打印出来,打印的结果为:2022-12-06T09:04:59.806
System.out.println("格式没有转换前的LocalDateTime的值为:" + localDateTime);
// 定义时间的格式
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 将当前时间按照定义好的时间格式进行格式化
String format = localDateTime.format(df);
// 打印格式化后的时间为:2022-12-06 09:04:59
System.out.println(format);

String类型转换成LocalDateTime类型

String localTime = "2022-12-06 09:09:09";
/**
 * 定义转换成LocalDateTime的格式
 * 【注意】:小时要用大写的HH,如果用小写的hh会报:java.time.format.DateTimeParseException异常
 */
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(localTime, dateTimeFormatter);
System.out.println(dateTime);

Date类型转换成String类型

// 获取时间戳
Long nowDateTime = System.currentTimeMillis();
// 创建Date对象
Date date = new Date();
// 定义Date类型转换成String类型的格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将时间戳赋值到Date对象中
date.setTime(nowDateTime);
// 格式化Date对象的值转换成字符串
String nowDateTimeString = simpleDateFormat.format(date);
System.out.println(nowDateTimeString);

String类型转换成Date类型

// 字符串转换成Date类型
String dateTime1 = "2022-12-06 09:36:36";
// 定义字符串转换成Date类型的格式
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parse = null;
try {
    // 将字符串传给SimpleDateFormat对象的parse作为参数
    parse = simpleDateFormat1.parse(dateTime1);
    System.out.println(parse);
} catch (ParseException e) {
    System.out.println("转换错了");
    throw new RuntimeException(e);
}

LocalDate类型转换成String类型

LocalDate localDate = LocalDate.now();
// LocalDate类型没有时分秒
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String format1 = localDate.format(formatter);
System.out.println(format1);

String类型转换成LocalDate类型

// 不能加时分秒,否则控制台会报java.time.format.DateTimeParseException异常
// String localDateNow = "2022-12-06 10:01:01";
String localDateNow = "2022-12-06";
LocalDate parse1 = LocalDate.parse(localDateNow);
System.out.println(parse1);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值