epoch에서 날짜 형식 변환
다음과 같은 날짜 형식의 문자열이 있습니다.
Jun 13 2003 23:11:52.454 UTC
밀리 세크가 포함되어 있습니다. 획기적으로 변환하고 싶습니다. 이 변환을 수행하는 데 사용할 수있는 Java 유틸리티가 있습니까?
이 코드는 java.text.SimpleDateFormat 을 사용 하여 문자열에서 java.util.Date 를 구문 분석하는 방법을 보여줍니다 .
String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454
Date.getTime()
에포크 시간을 밀리 초 단위로 반환합니다.
새로운 Java 8 API를 사용할 수도 있습니다.
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class StackoverflowTest{
public static void main(String args[]){
String strDate = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454
}
}
DateTimeFormatter
클래스는 이전을 대체합니다 SimpleDateFormat
. 그런 다음 ZonedDateTime
원하는 epoch 시간을 추출 할 수있는를 만들 수 있습니다 .
가장 큰 장점은 이제 스레드로부터 안전하다는 것입니다.
그의 발언과 제안에 대해 Basil Bourque에게 감사드립니다. 자세한 내용은 그의 답변을 읽으십시오.
tl; dr
ZonedDateTime.parse(
"Jun 13 2003 23:11:52.454 UTC" ,
DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" )
)
.toInstant()
.toEpochMilli()
1055545912454
java.time
이 답변 은 Lockni 의 답변에서 확장됩니다 .
DateTimeFormatter
먼저 DateTimeFormatter
개체 를 만들어 입력 문자열과 일치하는 형식 지정 패턴을 정의 합니다.
String input = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );
ZonedDateTime
문자열을 ZonedDateTime
. 해당 클래스를 ( Instant
+ ZoneId
) 로 생각할 수 있습니다 .
ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );
zdt.toString () : 2003-06-13T23 : 11 : 52.454Z [UTC]
시대부터 카운트
날짜-시간 값을 시대 로부터의 카운트로 추적하지 않는 것이 좋습니다 . 그렇게하면 인간이 숫자에서 의미있는 날짜-시간을 식별 할 수 없어서 잘못된 / 예기치 않은 값이 빠져 나갈 수 있으므로 디버깅이 까다로워집니다. 또한 이러한 카운트는 세분성 (전체 초, 밀리, 마이크로, 나노 등) 및 에포크 (다양한 컴퓨터 시스템에서 최소 24 인치)에서 모호합니다.
But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00
) through the Instant
class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.
Instant instant = zdt.toInstant ();
instant.toString(): 2003-06-13T23:11:52.454Z
long millisSinceEpoch = instant.toEpochMilli() ;
1055545912454
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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, Java SE 10, Java SE 11, and later - 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
- Most 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.
Create Common Method to Convert String to Date format
public static void main(String[] args) throws Exception {
long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}
private static long ConvertStringToDate(String dateString, String format) {
try {
return new SimpleDateFormat(format).parse(dateString).getTime();
} catch (ParseException e) {}
return 0;
}
String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
LocalDateTime zdt = LocalDateTime.parse(dateTime,dtf);
LocalDateTime now = LocalDateTime.now();
ZoneId zone = ZoneId.of("Asia/Kolkata");
ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
long a= zdt.toInstant(zoneOffSet).toEpochMilli();
Log.d("time","---"+a);
이 링크에서 영역 ID를 얻을 수 있습니다 !
참조 URL : https://stackoverflow.com/questions/6687433/convert-a-date-format-in-epoch
'programing' 카테고리의 다른 글
필드가 리플렉션을 통해 유형의 인스턴스인지 확인하는 방법은 무엇입니까? (0) | 2021.01.18 |
---|---|
숨겨진 항목을 제외한 JQuery 선택 입력 필드 (0) | 2021.01.18 |
동시성 : C ++ 11 메모리 모델의 원자 및 휘발성 (0) | 2021.01.18 |
예쁜 프린트 2D Python 목록 (0) | 2021.01.18 |
Python을 통해 연결할 때 기본 Mysql 연결 시간 제한을 어떻게 변경할 수 있습니까? (0) | 2021.01.18 |