我正在将
String
解析为 LocalDateTime
并以相反的方式返回。但解析器正在删除时间的 seconds 部分的零。
这个问题与另一个问题相关(不相同)。不过,我再次发布它,因为接受的响应提到使用
DateTimeFormatter
,我已经在使用它,您可以在下面的代码中看到我在 ISO_8601_PATTERN
变量中指定秒数。
我不确定我错过了什么或者我做错了什么。
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class Main
{
private final static String DEFAULT_PATTERN = "yyyy/MM/dd";
private final static String ISO_8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private final static String UTC_ZONE_ID = "UTC";
public static void main(String[] args) {
String stringDateTime = "2022-03-14T21:38:00Z";
LocalDateTime dateTime = fromIso8601(stringDateTime);
stringDateTime = toIso8601(dateTime);
System.out.println(stringDateTime);
// Prints: 2022-03-14T21:38Z
// Should print: 2022-03-14T21:38:00Z
}
public static LocalDateTime fromIso8601(String dateTimeString) {
return LocalDateTime.parse(dateTimeString,
DateTimeFormatter.ofPattern(ISO_8601_PATTERN).withZone(ZoneId.of(UTC_ZONE_ID)));
}
public static String toIso8601(LocalDateTime dateTime) {
return dateTime.atZone(ZoneOffset.UTC).toString();
}
}
使用 DateTimeFormatter 而不是 toString:
private final static String ISO_8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static String toIso8601(LocalDateTime dateTime) {
return DateTimeFormatter.ofPattern(ISO_8601_PATTERN).format(dateTime);
}
toString()
方法不添加零值:
//-----------------------------------------------------------------------
/**
* Outputs this time as a {@code String}, such as {@code 10:15}.
* <p>
* The output will be one of the following ISO-8601 formats:
* <ul>
* <li>{@code HH:mm}</li>
* <li>{@code HH:mm:ss}</li>
* <li>{@code HH:mm:ss.SSS}</li>
* <li>{@code HH:mm:ss.SSSSSS}</li>
* <li>{@code HH:mm:ss.SSSSSSSSS}</li>
* </ul>
* 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 time, not null
*/
@Override
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();
}