유닉스 시간(Unix Time)은 UNIX time 이란, 1970년 1월 1일 00:00:00 UTC 로부터 현재까지의 누적된 초(seconds) 값을 의미한다. 초(seconds) 값으로, 정수형으로 나타낸다.
자바에서 정수형의 Unix Timestamp를 원하는 Date 형식으로 변환하여 사용하는 부분을 다뤄본다. 우리나라는 유닉스 시간의 기준시(UTC)와 9시간이 차이나기 때문에, 이 부분을 잘 고려해서 변환하면 된다.
private static String unixTimestampToDate(Long unixTimestamp) {
//unix timestamp(Sec)를 date 타입으로 변환하기 위해 ms단위에 맞게 *1000
Date date = new Date(unixTimestamp * 1000L);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//한국시간에 맞게 timezone 설정(GMT+9)
sdf.setTimeZone(TimeZone.getTimeZone("GMT+9"));
String formattedDate = sdf.format(date);
return formattedDate;
}
public static void main(String[] args) {
//현재 Unix time을 불러온다
Long unixTime = (Long) (System.currentTimeMillis() / 1000);
System.out.println("Now UTC TIME " + unixTime);
//날짜 형식의 문자열로 변환
String dateStr = unixTimestampToDate(unixTime);
System.out.println("dateTime="+dateStr);
}
위의 코드를 실행하면 당시 코드를 실행한 시간의 유닉스 시간과, 우리가 알아볼 수 있는 날짜 형식으로 변환된 시간을 확인 할 수 있다.
'Language > JAVA' 카테고리의 다른 글
배열(Array) 복사를 이용한 배열 자르기 (0) | 2022.06.05 |
---|