我正在尝试将格式为“01/02/2018 02:48:04 PM”的字符串转换为 smalldatetime 格式以插入 MS SQL。
import java.sql.Date;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class TimeStampTest {
public static void main(String[] args) {
String originalDate ="01/02/2018 02:29:23 PM";
System.out.println(convertToSmallDatetimeFormat(originalDate));
}
private static Timestamp convertToSmallDatetimeFormat(String originalDate) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MM/dd/yyyy hh:mm:ss a")
.toFormatter(Locale.US);
LocalDateTime localDate = LocalDateTime.parse(originalDate,formatter);
return new Timestamp(localDate.getNano()/1000000);
}
}
但是我意识到当我执行以下代码时
LocalDateTime localDate = LocalDateTime.parse(originalDate,formatter);
我得到了一些垃圾价值 2018-01-02T15:58:04
这导致 localDate.getNano() 为 0