IT박스

Java에서 현재 타임 스탬프를 문자열 형식으로 얻는 방법은 무엇입니까?

itboxs 2020. 6. 10. 22:54
반응형

Java에서 현재 타임 스탬프를 문자열 형식으로 얻는 방법은 무엇입니까? “yyyy.MM.dd.HH.mm.ss”


Java에서 문자열 형식의 타임 스탬프를 얻는 방법은 무엇입니까? "yyyy.MM.dd.HH.mm.ss"

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Timestamp());

이것이 내가 가지고 있지만 Timestamp ()에는 매개 변수가 필요합니다 ...


바꾸다

new Timestamp();

new java.util.Date()

에 대한 기본 생성자가 없기 때문에 Timestamp또는 메소드를 사용하여 수행 할 수 있습니다.

new Timestamp(System.currentTimeMillis());

java.util.Date타임 스탬프 대신 클래스를 사용하십시오 .

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

이렇게하면 지정된 형식으로 현재 날짜가 표시됩니다.


Timestamp 대신 java.util.Date를 사용할 수 있습니다.

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

tl; dr

최신 java.time 클래스 만 사용하십시오 . 절대로 같은 끔찍한 기존의 클래스를 사용하지 않는 SimpleDateFormat, Date또는 java.sql.Timestamp.

ZonedDateTime                    // Represent a moment as perceived in the wall-clock time used by the people of a particular region ( a time zone).
.now(                            // Capture the current moment.
    ZoneId.of( "Africa/Tunis" )  // Specify the time zone using proper Continent/Region name. Never use 3-4 character pseudo-zones such as PDT, EST, IST. 
)                                // Returns a `ZonedDateTime` object. 
.format(                         // Generate a `String` object containing text representing the value of our date-time object. 
    DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" )
)                                // Returns a `String`. 

java.time 및 JDBC 4.2

현대적인 접근법은 위에서 본 java.time 클래스를 사용합니다 .

JDBC 드라이버가 JDBC 4.2를 준수 하는 경우 데이터베이스와 java.time 오브젝트를 직접 교환 할 수 있습니다 . PreparedStatement::setObject및을 사용하십시오 ResultSet::getObject.

JDBC 4.2 이전의 드라이버에만 java.sql을 사용하십시오.

JDBC 드라이버가 java.time 유형 지원을 위해 JDBC 4.2를 아직 준수하지 않으면 java.sql 클래스 사용으로 폴백해야합니다.

데이터 저장

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;  // Capture the current moment in UTC.
myPreparedStatement.setObject( … , odt ) ;

데이터를 검색하는 중입니다.

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

와 같은 java.sql 유형 java.sql.Timestamp은 데이터베이스 내외부 전송에만 사용해야합니다. Java 8 이상에서 즉시 java.time 유형으로 변환하십시오.

java.time.Instant

A는 java.sql.TimestampA를 매핑 java.time.Instant, UTC의 타임 라인에 잠시.

java.sql.Timestamp ts = myResultSet.getTimestamp( … );
Instant instant = ts.toInstant(); 

시간대

원하는 / 예상 시간대를 적용하여를 얻으십시오 ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

형식화 된 문자열

a DateTimeFormatter를 사용하여 문자열을 생성하십시오. 패턴 코드는 코드 코드와 유사 java.text.SimpleDateFormat하지만 정확하게는 아니므로 문서를주의 깊게 읽으십시오.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" );
String output = zdt.format( formatter );

이 특정 형식은 UTC에서 오프셋 또는 시간대 표시가 없기 때문에 정확한 의미는 모호 합니다.

ISO 8601

이 문제에 대해 언급이있는 경우 직접 롤링하는 대신 표준 ISO 8601 형식을 사용하는 것이 좋습니다 . 표준 형식은 귀하의 형식과 매우 유사합니다. 예를 들면 다음과 같습니다
2016-02-20T03:26:32+05:30..

java.time 클래스는 기본적으로 이러한 표준 형식을 사용하므로 패턴을 지정할 필요가 없습니다. ZonedDateTime클래스는 표준 시간대 이름을 추가하여 표준 형식을 확장합니다 (현명한 개선).

String output = zdt.toString(); // Example: 2007-12-03T10:15:30+01:00[Europe/Paris]

java.sql로 변환

You can convert from java.time back to java.sql.Timestamp. Extract an Instant from the ZonedDateTime.

New methods have been added to the old classes to facilitate converting to/from java.time classes.

java.sql.Timestamp ts = java.sql.Timestamp.from( zdt.toInstant() );

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?

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.


A more appropriate approach is to specify a Locale region as a parameter in the constructor. The example below uses a US Locale region. Date formatting is locale-sensitive and uses the Locale to tailor information relative to the customs and conventions of the user's region Locale (Java Platform SE 7)

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss", Locale.US).format(new Date());

You can use the following

new java.sql.Timestamp(System.currentTimeMillis()).getTime()

Result : 1539594988651

Hope this will help. Just my suggestion and not for reward points.


Use below code to get current timestamps:

Timestamp ts = new Timestamp(date.getTime());

For reference

How to get current timestamps in Java

참고URL : https://stackoverflow.com/questions/23068676/how-to-get-current-timestamp-in-string-format-in-java-yyyy-mm-dd-hh-mm-ss

반응형