简体   繁体   English

将 LocalDateTime Object 转换为 LocalDateTime

[英]Converting LocalDateTime Object to LocalDateTime

I am new to Java and I am working on Java 8.我是 Java 的新手,我正在研究 Java 8。

I am trying to convert LocalDateTime Object to LocalDateTime but not able to find any way without converting it to String.我正在尝试将 LocalDateTime Object 转换为 LocalDateTime 但如果不将其转换为字符串就找不到任何方法。 Is there any direct method for converting Object to LocalDateTime when the underlying Object type is LocalDateTime?当底层 Object 类型为 LocalDateTime 时,是否有任何直接的方法可以将 Object 转换为 LocalDateTime?

Moreover, if there is any way to convert, can it work for underlying String type LocalDateTime Object too?此外,如果有任何转换方法,它是否也适用于底层字符串类型 LocalDateTime Object ?

Below is my current code which is converting the Object to String before converting it to LocalDateTime as LocalDateTime.parse method needs String input.下面是我当前的代码,它将 Object 转换为字符串,然后再将其转换为 LocalDateTime,因为 LocalDateTime.parse 方法需要输入字符串。

public static LocalDateTime toDateTime(Object dateTimeObject) {
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeObject.toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
    
    return dateTime;
}

If the object is a LocalDateTime , you can cast the object.如果 object 是LocalDateTime ,则可以转换 object。

public static LocalDateTime toDateTime(Object dateTimeObject) {
    if (dateTimeObject instanceof LocalDateTime) {
        return (LocalDateTime) dateTimeObject;
    }
    return null;
}

According to the Java 8 LocalDateTime API there is no method that takes an Object argument and returns a LocalDateTime.根据Java 8 LocalDateTime API没有采用 Object 参数并返回 LocalDateTime 的方法。 But there is one that takes a CharSequence parameter, which is why it works when you convert the object to String, and why it won't work if you just pass the Object parameter.但是有一个采用 CharSequence 参数,这就是为什么当您将 object 转换为 String 时它可以工作的原因,以及为什么如果您只传递 Object 参数它不会工作的原因。 If you don't want to have to do the call to the toString() method, perhaps the parameter of toDateTime(Object o) should be of a different type.如果您不想调用 toString() 方法,也许 toDateTime(Object o) 的参数应该是不同的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM