Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

달력 연도의 날짜를 다른 형식으로 표시하는 Java 프로그램

<시간/>

이 기사에서는 달력 연도의 날짜를 다른 형식으로 표시하는 방법을 이해합니다. Java에는 내장된 Date 클래스가 없지만 날짜 및 시간 API와 함께 작동하도록 java.time 패키지를 가져올 수 있습니다. 패키지에는 많은 날짜 및 시간 클래스가 포함되어 있습니다.

아래는 동일한 데모입니다 -

입력이 다음과 같다고 가정 -

프로그램 실행

원하는 출력은 -

첫 번째 날짜 형식은:2022-03-17T23:37:37.623304800두 번째 날짜 형식은:17/03/2022세 번째 날짜 형식은:2022년 3월 17일 목요일

알고리즘

1단계 - START2단계 - LocalDateTime의 개체 즉 date를 선언합니다. 3단계 - 값을 정의합니다. 4단계 - DateTimeFormatter 개체를 사용하여 다른 날짜 시간 형식을 정의합니다. 5단계 - 다른 날짜 시간 형식을 표시합니다. 6단계 - 중지

예시 1

여기에서 모든 작업을 'main' 기능 아래에 묶습니다.

import java.time.*;import java.time.format.DateTimeFormatter;public class Demo { public static void main(String[] args){ System.out.println("필수 패키지를 가져왔습니다."); LocalDateTime 날짜 =LocalDateTime.now(); System.out.println("LocalDateTime 객체가 정의되었습니다."); System.out.println("\n첫 번째 날짜 형식은:" +date); DateTimeFormatter date_format_1 =DateTimeFormatter.ofPattern("dd/MM/yyyy"); 문자열 formattedDate_1 =date.format(date_format_1); System.out.println("\n두 번째 날짜 형식은:" +formattedDate_1); DateTimeFormatter date_format_2 =DateTimeFormatter.ofPattern("EEEE, dd MMM yyyy"); 문자열 formattedDate_2 =date.format(date_format_2); System.out.println("\n세 번째 날짜 형식은 다음과 같습니다." +formattedDate_2); }}

출력

필수 패키지를 가져왔습니다.LocalDateTime 개체가 정의되었습니다.첫 번째 날짜 형식:2022-03-29T08:53:19.809두 번째 날짜 형식:2022-03-29세 번째 날짜 형식:2022년 3월 29일 화요일 

예시 2

여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.

가져오기 java.time.*;가져오기 java.time.format.DateTimeFormatter, public class Demo { static void print_date_format(LocalDateTime 날짜){ DateTimeFormatter date_format_1 =DateTimeFormatter.ofPattern("dd/MM/yyyy"); 문자열 formattedDate_1 =date.format(date_format_1); System.out.println("\n두 번째 날짜 형식은:" +formattedDate_1); DateTimeFormatter date_format_2 =DateTimeFormatter.ofPattern("EEEE, dd MMM yyyy"); 문자열 formattedDate_2 =date.format(date_format_2); System.out.println("\n세 번째 날짜 형식은 다음과 같습니다." +formattedDate_2); } public static void main(String[] args){ System.out.println("필요한 패키지를 가져왔습니다."); LocalDateTime 날짜 =LocalDateTime.now(); System.out.println("LocalDateTime 객체가 정의되었습니다."); System.out.println("\n첫 번째 날짜 형식은:" +date); print_date_format(날짜); }}

출력

필수 패키지를 가져왔습니다.LocalDateTime 개체가 정의되었습니다.첫 번째 날짜 형식은:2022-03-29T08:53:58.155두 번째 날짜 형식은:29/03/2022입니다.세 번째 날짜 형식은:2022년 3월 29일 화요일