java8中LocalDateTime解析日期的示例分享

2022/7/1 1:20:58

本文主要是介绍java8中LocalDateTime解析日期的示例分享,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

转自:

  http://www.java265.com/JavaJingYan/202205/16521663003330.html

Date对象:

     在java中用于存储日期信息的一个对象

LocalDateTime简介:

    java.time.LocalDateTime是一个可以表示日期时间的对象,代表日期时间

    通常被视为年 - 月 - 日 - 时 - 分 - 秒,也提供了其他日期和时间字段

    如星期。LocalDateTime的时间精度为纳秒精度(1秒=1000毫秒,1毫秒=1000微秒,1微秒=1000纳秒)

下文笔者讲述LocalDateTime解析日期的方法分享,如下所示:

实现思路:
     1.定义一个DateTimeFormatter
     2.使用LocalDateTime.parse方法可格式化一个DateTimeFormatter
	   即可将日期转换为指定样式

例:

     将字符串转换为LocalDateTime对象

     使用localDateTime中的parse方法结合datetimeformater即可转换

package com.java265.other;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.util.Locale;
public class Test01 {
	/*
	 * java265.com 示例程序
	 */
	public static void main(String[] args) {
		String dateFormat = "HH:mm:ss MM/dd/uuuu";
		String dateString = "15:03:56 05/29/2022";
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat, Locale.US)
				.withResolverStyle(ResolverStyle.STRICT);
		try {
			LocalDateTime date = LocalDateTime.parse(dateString, dateTimeFormatter);
			System.out.println(date);
		} catch (DateTimeParseException e) {
			System.out.println("Exception was thrown");
		}
	}
}


这篇关于java8中LocalDateTime解析日期的示例分享的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程