转载自 https://blog.csdn.net/s1ngle/article/details/125947190
做一个项目,快完工的时候,突然发现一个缺陷:用LocalDateTime格式的时间转化为String类型时,如果时间刚好在00秒,转化过来的字符串丢掉了秒位,从而导致后面的格式转化出错。在网上搜了搜,解决方法是先用DateTimeFormatter规定好日期格式,然后再用format方法转化为字符串。我试了试,确实可行。但至于为什么会丢失秒位,还是不知道其原因。
回去看了看源码,原因其实很简单
下面上个例子:
public static void main(String[] args){
LocalDateTime now = LocalDateTime.of(2022,07,23,12,30,00);
System.out.println(now);
String nowStr = now.toString();
System.out.println(nowStr);
String valueOfNow = String.valueOf(now);
System.out.println(valueOfNow);
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String parseStr = now.format(format);
System.out.println(parseStr);
/**
* output:
* 2022-07-23T12:30
* 2022-07-23T12:30
* 2022-07-23T12:30
* 2022-07-23 12:30:00
*/
}
前三个输出语句输出的内容都不是我们想要的,只有最后一个才是。但是为什么会造成这样的结果呢?原因其实很简单。
首先看第一个:
我直接打印了now,打印内容少了秒位,为了确定我的变量now里面确确实实存了秒位,开调试看了一下
确定变量没有问题,那么就只可能是打印的方法println()的问题了,看了一下println方法的实现
/**
* Prints an Object and then terminate the line. This method calls
* at first String.valueOf(x) to get the printed object’s string value,
* then behaves as
* though it invokes {@link #print(String)}
and then
* {@link #println()}
.
*
* @param x The Object
to be printed.
*/
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
它是先用String.valueOf()方法将参数对象转化成了字符串,然后打印输出了字符串。那么问题就可能出现在String.valueOf()这里了。
接着看第二个和第三个:
我先将now用String.valueOf()和object.toString()转化成了字符串,然后再打印了一下,结果和第一个一样。到这里,问题就基本锁定在String.valueOf()和object.toString()这两个方法上了。
String.valueOf():
看一下String.valueOf()的源码:
/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code “null”}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? “null” : obj.toString();
}
原来它调的还是toString()方法,那么我们的目光就转到了toString()上
LocalDateTime.toString():
看一下LocalDateTime.toString()干了什么:
/**
* Outputs this date-time as a {@code String}, such as {@code 2007-12-03T10:15:30}.
*
* The output will be one of the following ISO-8601 formats:
*
*- {@code uuuu-MM-dd’T’HH:mm}
*- {@code uuuu-MM-dd’T’HH:mm:ss}
*- {@code uuuu-MM-dd’T’HH:mm:ss.SSS}
*- {@code uuuu-MM-dd’T’HH:mm:ss.SSSSSS}
*- {@code uuuu-MM-dd’T’HH:mm:ss.SSSSSSSSS}
*
* The format used will be the shortest that outputs the full value of
* the time where the omitted parts are implied to be zero.
*
* @return a string representation of this date-time, not null
*/
@Override
public String toString() {
return date.toString() + ‘T’ + time.toString();
}
那么继续看time的toString()方法
(细心的人可能已经在上面的截图中看出来了,LocalDateTime相当于LocalDate+LocalTime)
public String toString() {
StringBuilder buf = new StringBuilder(18);
int hourValue = hour;
int minuteValue = minute;
int secondValue = second;
int nanoValue = nano;
buf.append(hourValue < 10 ? “0” : “”).append(hourValue)
.append(minuteValue < 10 ? “:0” : “:”).append(minuteValue);
if (secondValue > 0 || nanoValue > 0) {
buf.append(secondValue < 10 ? “:0” : “:”).append(secondValue);
if (nanoValue > 0) {
buf.append(‘.’);
if (nanoValue % 1000_000 == 0) {
buf.append(Integer.toString((nanoValue / 1000_000) + 1000).substring(1));
} else if (nanoValue % 1000 == 0) {
buf.append(Integer.toString((nanoValue / 1000) + 1000_000).substring(1));
} else {
buf.append(Integer.toString((nanoValue) + 1000_000_000).substring(1));
}
}
}
return buf.toString();
}
看到这么长一串就知道事情不简单了,原来是当秒数等于0或纳秒数等于0的时候,toString方法就不会再追加秒位和纳秒位。所以才会导致我们直接用LocalDateTime的toString()方法会丢失秒位。
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/s1ngle/article/details/125947190