Convert Date between LocalDateTime
2002 단어 DateTime
Java8 has new date and time classes to “replace” the old not-so-beloved java.util.Date class.
Unfortunately though, converting between the two is somewhat less obvious than you might expect.
Convert java.util.Date to java.time.LocalDateTime
Date ts = ...;
Instant instant = Instant.ofEpochMilli(ts.getTime());
LocalDateTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
The big trick (for all these conversions) is to convert to Instant. This can be converted to LocalDateTime by telling the system which timezone to use. This needs to be the system default locale, otherwise the time will change.
Convert java.util.Date to java.time.LocalDate
Date date = ...;
Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDate res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();
Convert java.util.Date to java.time.LocalTime
Date time = ...;
Instant instant = Instant.ofEpochMilli(time.getTime());
LocalTime res = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalTime();
Convert java.time.LocalDateTime to java.util.Date
LocalDateTime ldt = ...;
Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();
Date res = Date.from(instant);
Convert java.time.LocalDate to java.util.Date
LocalDate ld = ...;Instant instant = ld.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date res = Date.from(instant);
Convert java.time.LocalTime to java.util.Date
LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);
This one is a little, funny, you need to inject a date to convert the time… Gives you the option of start of epoch or something else.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
django에서 시간 범위에 따라 데이터베이스 조회웹 폼에서 사용자가 지정한 시간 범위를 가져와 데이터베이스에서 이 시간 범위 내의 데이터를 조회하는 간단한 기능을 소개합니다.데이터베이스의 모델은 다음과 같습니다. 우리가 폼에서 얻은 Request를 가정해 보세요....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.