English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 프로그램에서는 Java 형식으로 현재 날짜와 시간을 가져오는 방법을 배울 것입니다.
import java.time.LocalDateTime; public class CurrentDateTime {}} public static void main(String[] args) { LocalDateTime current = LocalDateTime.now(); System.out.println("현재 날짜와 시간은: " + current); } }
이 프로그램을 실행하면, 출력은 다음과 같습니다:
현재 날짜와 시간은: 2019-08-02T11:25:44.973
위의 프로그램에서는 LocalDateTime.now() 메서드를 사용하여 현재 날짜와 시간을 변수 current에 저장했습니다
기본 형식은 toString() 메서드를 사용하여 LocalDateTime 객체에서 문자열로 변환하면 됩니다
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class CurrentDateTime {}} public static void main(String[] args) { LocalDateTime current = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); String formatted = current.format(formatter); System.out.println("현재 날짜와 시간은: " + formatted); } }
이 프로그램을 실행하면, 출력은 다음과 같습니다:
현재 날짜와 시간은: 2017-08-02 11:29:57.401
위의 프로그램에서는 DateTimeFormatter 객체를 사용하여 Year 형식을 정의했습니다-Month-Day Hours:Minutes:Seconds.Milliseconds 패턴
그런 다음, LocalDateTime의 format() 메서드를 사용하여 주어진 formatter를 사용합니다. 이렇게 하면 형식화된 문자열 출력을 얻을 수 있습니다.
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class CurrentDateTime {}} public static void main(String[] args) { LocalDateTime current = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE; String formatted = current.format(formatter); System.out.println("현재 날짜는: " + formatted); } }
이 프로그램을 실행하면, 출력은 다음과 같습니다:
현재 날짜는: 20170802
위의 프로그램에서는 예약된 형식 상수 BASIC_ISO_DATE를 사용하여 현재 ISO 날짜를 출력으로 가져오었습니다.
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; public class CurrentDateTime {}} public static void main(String[] args) { LocalDateTime current = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM); String formatted = current.format(formatter); System.out.println("현재 날짜는: " + formatted); } }
이 프로그램을 실행하면, 출력은 다음과 같습니다:
현재 날짜는: Aug 2, 2017 11:44:19 AM
위의 프로그램에서는 지정된 형식으로 현재 날짜와 시간을 가져오기 위해 로컬라이제이션 스타일 Medium을 사용했습니다. 다른 스타일들도 있습니다: Full, Long, Short.