LocalDate를 LocalDateTime 또는 java.sql.Timestamp로 변환
JodaTime 1.6.2를 사용하고 있습니다.
나는 LocalDate
(Joda) LocalDateTime
또는 java.sqlTimestamp
ormapping 으로 변환해야한다는 것을 가지고 있습니다 .
그 이유는 a LocalDateTime
와 a 사이를 변환하는 방법을 알아 냈기 때문입니다 java.sql.Timestamp
.
LocalDateTime ldt = new LocalDateTime();
DateTimeFormatter dtf = DateTimeFormatter.forPattern("yyyy-MM-dd HH:mm:ss");
Timestamp ts = Timestamp.valueOf(ldt.toString(dtf));
따라서 LocalDate
and 사이 만 변환 할 수 있으면로 LocalDateTime
계속 변환 할 수 java.sql.Timestamp
있습니다. 올바른 방향으로 조금도 감사합니다!
JodaTime
JodaTime의 변환하기 org.joda.time.LocalDate
위해 java.sql.Timestamp
, 단지 할
Timestamp timestamp = new Timestamp(localDate.toDateTimeAtStartOfDay().getMillis());
JodaTime의 변환하기 org.joda.time.LocalDateTime
위해 java.sql.Timestamp
, 단지 할
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
자바 타임
Java8의 변환하기 java.time.LocalDate
위해 java.sql.Timestamp
, 단지 할
Timestamp timestamp = Timestamp.valueOf(localDate.atStartOfDay());
Java8의 변환하기 java.time.LocalDateTime
위해 java.sql.Timestamp
, 단지 할
Timestamp timestamp = Timestamp.valueOf(localDateTime);
가장 좋은 방법은 Java 8 시간 API를 사용하는 것입니다.
LocalDateTime ldt = timeStamp.toLocalDateTime();
Timestamp ts = Timestamp.valueOf(ldt);
JPA와 함께 사용하여 모델과 함께 사용하십시오 ( https://weblogs.java.net/blog/montanajava/archive/2014/06/17/using-java-8-datetime-classes-jpa ).
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime ldt) {
return Timestamp.valueOf(ldt);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp ts) {
return ts.toLocalDateTime();
}
}
이제는 표준 시간대 독립 시간입니다. 또한 쉽습니다.
LocalDate ld = ldt.toLocalDate();
LocalTime lt = ldt.toLocalTime();
포맷팅 :
DateTimeFormatter DATE_TME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
String str = ldt.format(DATE_TME_FORMATTER);
ldt = LocalDateTime.parse(str, DATE_TME_FORMATTER);
업데이트 : postgres 9.4.1208, HSQLDB 2.4.0 등은 대화없이 Java 8 Time API를 이해합니다!
tl; dr
Joda 타임 프로젝트는 지금 대체 유지 보수 모드에 java.time의 클래스.
- 그냥
java.time.Instant
수업을 사용하십시오 . - 필요 없음 :
LocalDateTime
java.sql.Timestamp
- 현
UTC로 현재 순간을 캡처합니다.
Instant.now()
해당 순간을 데이터베이스에 저장하려면 다음을 수행하십시오.
myPreparedStatement.setObject( … , Instant.now() ) // Writes an `Instant` to database.
datbase에서 해당 순간을 검색하려면
myResultSet.getObject( … , Instant.class ) // Instantiates a `Instant`
벽시계 시간을 특정 시간대의 시간으로 조정합니다.
instant.atZone( z ) // Instantiates a `ZonedDateTime`
LocalDateTime
잘못된 수업입니까
다른 답변은 정확하지만 LocalDateTime
목적에 맞지 않는 수업 이라고 지적하지는 않습니다 .
In both java.time and Joda-Time, a LocalDateTime
purposely lacks any concept of time zone or offset-from-UTC. As such, it does not represent a moment, and is not a point on the timeline. A LocalDateTime
represents a rough idea about potential moments along a range of about 26-27 hours.
Use a LocalDateTime
for either when the zone/offset is unknown (not a good situation), or when the zone-offset is indeterminate. For example, “Christmas starts at first moment of December 25, 2018” would be represented as a LocalDateTime
.
Use a ZonedDateTime
to represent a moment in a particular time zone. For example, Christmas starting in any particular zone such as Pacific/Auckland
or America/Montreal
would be represented with a ZonedDateTime
object.
For a moment always in UTC, use Instant
.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Apply a time zone. Same moment, same point on the timeline, but viewed with a different wall-clock time.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
So, if I can just convert between LocalDate and LocalDateTime,
No, wrong strategy. If you have a date-only value, and you want a date-time value, you must specify a time-of-day. That time-of-day may not be valid on that date for a particular zone – in which case ZonedDateTime
class automatically adjusts the time-of-day as needed.
LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;
LocalTime lt = LocalTime.of( 14 , 0 ) ; // 14:00 = 2 PM.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
If you want the first moment of the day as your time-of-day, let java.time determine that moment. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00.
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
java.sql.Timestamp
is the wrong class
The java.sql.Timestamp
is part of the troublesome old date-time classes that are now legacy, supplanted entirely by the java.time classes. That class was used to represent a moment in UTC with a resolution of nanoseconds. That purpose is now served with java.time.Instant
.
JDBC 4.2 with getObject
/setObject
As of JDBC 4.2 and later, your JDBC driver can directly exchange java.time objects with the database by calling:
For example:
myPreparedStatement.setObject( … , instant ) ;
… and …
Instant instant = myResultSet.getObject( … , Instant.class ) ;
Convert legacy ⬌ modern
If you must interface with old code not yet updated to java.time, convert back and forth using new methods added to the old classes.
Instant instant = myJavaSqlTimestamp.toInstant() ; // Going from legacy class to modern class.
…and…
java.sql.Timestamp myJavaSqlTimestamp = java.sql.Timestamp.from( instant ) ; // Going from modern class to legacy class.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Depending on your timezone, you may lose a few minutes (1650-01-01 00:00:00 becomes 1649-12-31 23:52:58)
Use the following code to avoid that
new Timestamp(localDateTime.getYear() - 1900, localDateTime.getMonthOfYear() - 1, localDateTime.getDayOfMonth(), localDateTime.getHourOfDay(), localDateTime.getMinuteOfHour(), localDateTime.getSecondOfMinute(), fractional);
Since Joda is getting faded, someone might want to convert LocaltDate
to LocalDateTime
in Java 8. In Java 8 LocalDateTime
it will give a way to create a LocalDateTime
instance using a LocalDate
and LocalTime
. Check here.
public static LocalDateTime of(LocalDate date, LocalTime time)
Sample would be,
// just to create a sample LocalDate
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
// convert ld into a LocalDateTime
// We need to specify the LocalTime component here as well, it can be any accepted value
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00
Just for reference, For getting the epoch seconds below can be used,
ZoneId zoneId = ZoneId.systemDefault();
long epoch = ldt.atZone(zoneId).toEpochSecond();
// If you only care about UTC
long epochUTC = ldt.toEpochSecond(ZoneOffset.UTC);
function call asStartOfDay()
on java.time.LocalDate
object returns a java.time.LocalDateTime
object
Java8 +
import java.time.Instant;
Instant.now().getEpochSecond(); //timestamp in seconds format (int)
Instant.now().toEpochMilli(); // timestamp in milliseconds format (long)
참고URL : https://stackoverflow.com/questions/8992282/convert-localdate-to-localdatetime-or-java-sql-timestamp
'developer tip' 카테고리의 다른 글
ViewPager에서 탭을 사용할 때 "Java.lang.IllegalStateException 활동이 삭제되었습니다"오류가 발생 함 (0) | 2020.08.03 |
---|---|
지정된 브라우저 (예 : Chrome)에서 파일을 여는 Sublime Text 2 키보드 단축키 (0) | 2020.08.03 |
Java 패키지에서 특성 파일로드 (0) | 2020.08.03 |
자동 레이아웃 : Top Layout Guide가 아닌 Superview에 구속 조건을 추가 하시겠습니까? (0) | 2020.08.02 |
설정된 최하위 비트의 위치 (0) | 2020.08.02 |