将LocalDateTime对象转换为LocalDateTime

huangapple go评论146阅读模式
英文:

Converting LocalDateTime Object to LocalDateTime

问题

我刚接触Java,并且正在使用Java 8。

我试图将LocalDateTime对象转换为LocalDateTime,但是在不将其转换为字符串的情况下找不到任何方法。在底层对象类型为LocalDateTime时,是否有任何直接的方法可以将对象转换为LocalDateTime?

此外,如果有任何转换的方法,是否可以用于底层字符串类型的LocalDateTime对象?

以下是我当前的代码,它将对象转换为字符串,然后再将其转换为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;
}
英文:

I am new to Java and I am working on Java 8.

I am trying to convert LocalDateTime Object to LocalDateTime but not able to find any way without converting it to String. Is there any direct method for converting Object to LocalDateTime when the underlying Object type is LocalDateTime?

Moreover, if there is any way to convert, can it work for underlying String type LocalDateTime Object too?

Below is my current code which is converting the Object to String before converting it to LocalDateTime as LocalDateTime.parse method needs String input.

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

答案1

得分: 1

如果对象是 LocalDateTime,您可以将对象强制转换。

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

If the object is a LocalDateTime, you can cast the object.

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

答案2

得分: 0

根据Java 8 LocalDateTime API,没有接受Object参数并返回LocalDateTime的方法。但是有一个接受CharSequence参数的方法,这就是为什么当您将对象转换为String时它起作用,以及为什么如果您只传递Object参数,它就不起作用。如果您不想调用toString()方法,也许toDateTime(Object o)的参数应该是不同类型的。

英文:

According to the Java 8 LocalDateTime API there is no method that takes an Object argument and returns a 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. 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.

huangapple
  • 本文由 发表于 2020年8月17日 18:17:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63448852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定