자바 날짜 불러 오기 - jaba naljja bulleo ogi

includestdio

컴퓨터

[Java] 현재날짜 구하기

includestdio 2014. 8. 25. 23:46

1. 형식에 맞추어 날짜 출력하는 방법

- SimpleDateFormat을 이용해 형식을 지정

- 예제 코드

1

2

3

4

SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat ( "yyyy.MM.dd HH:mm:ss", Locale.KOREA );

Date currentTime = new Date ();

String mTime = mSimpleDateFormat.format ( currentTime );

System.out.println ( mTime );

2. 현재 년, 월, 일, 시, 분, 초 구하기

- 예제 코드

1

2

3

4

5

6

7

8

9

10

11

12

Calendar cal = Calendar.getInstance();

//현재 년도, 월, 일

int year = cal.get ( cal.YEAR );

int month = cal.get ( cal.MONTH ) + 1 ;

int date = cal.get ( cal.DATE ) ;

//현재 (시,분,초)

int hour = cal.get ( cal.HOUR_OF_DAY ) ;

int min = cal.get ( cal.MINUTE );

int sec = cal.get ( cal.SECOND );

3. 자바의 기본 날짜/시간 포맷으로 간단하게 출력

1

2

3

4

5

Date date = new Date();

System.out.println(date);

// 현재 날짜 출력

날짜 계산 하는 방법을 간단하게 기록해보려고 합니다.

아래처럼 작성하시면 쉽게 구하실 수 있습니다.

SImpleDateFormat에서 인자 값 두개 중 뒷부분인 Locale.KOREA 는 빼셔도 됩니다.

저는 한국 기준으로 맞추기 위해서 이렇게 했습니다. 

< 오늘 날짜 계산하는 방법 >

Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH", Locale.KOREA);

String today = sdf.format(date);

cs

< 어제 날짜 계산하는 방법 >

Date dDate = new Date();

dDate = new Date(dDate.getTime()+(1000*60*60*24*-1));

SimpleDateFormat dSdf = new SimpleDateFormat("yyyy/MM/dd HH", Locale.KOREA);

String yesterday = dSdf.format(dDate);

cs

자바에서 현재 날짜와 시간을 출력해주는 방법은 아주 다양합니다. 그 다양한 방법중에서 대표적으로 3가지가 주로 사용되고 있죠. Date객체를 사용하는 방법, Calendar클래스의 getInstance() 메서드를 활용하는 방법, System클래스의 currentTimeMillis() 메스드를 활용하는 방법이 바로 그것입니다. 이번 포스팅에서는 현재날짜, 현재시간을 원하는 형태로 포맷팅하여 출력하는 방법에 대해 알아보도록 하겠습니다.

1. Date객체를 활용하는 방법 

SimpleDateFormat format1 = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss");
SimpleDateFormat format2 = new SimpleDateFormat ( "yyyy년 MM월dd일 HH시mm분ss초");
		
Date time = new Date();
		
String time1 = format1.format(time);
String time2 = format2.format(time);
		
System.out.println(time1);
System.out.println(time2);

2. Calendar클래스의 getInstance()메서드를 활용하는 방법 

SimpleDateFormat format1 = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss");
SimpleDateFormat format2 = new SimpleDateFormat ( "yyyy년 MM월dd일 HH시mm분ss초");
		
Calendar time = Calendar.getInstance();
       
String format_time1 = format1.format(time.getTime());
String format_time2 = format2.format(time.getTime());
        
System.out.println(format_time1);
System.out.println(format_time2);

3. System클래스의 currentTimeMillis()메서드를 활용하는 방법 

SimpleDateFormat format1 = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss");
SimpleDateFormat format2 = new SimpleDateFormat ( "yyyy년 MM월dd일 HH시mm분ss초");
		
String format_time1 = format1.format (System.currentTimeMillis());
String format_time2 = format2.format (System.currentTimeMillis());
        				 		
 System.out.println(format_time1);
 System.out.println(format_time2);
자바 날짜 불러 오기 - jaba naljja bulleo ogi

[Java] ArrayList로 구현한 Memory구조(Stack,Pop)

[Java] BufferedReader, BufferedWriter를 활용한 빠른 입출력