프로그래밍/안드로이드

안드로이드 - 날짜 시간 나타내기

가카리 2015. 8. 8. 15:16
반응형

 

현재 날짜와 시간을 구하는 가장 쉬운 방법은 System의 다음 정적 메소드를 사용하는 것이다.

 

static long currentTimeMillis()

 

이 메소드는 현재 시간값을 정수 하나로 리턴하는데 이 값은 1970년 1월 1일 자정을 기준으로 한 1/1000초 단위 경과시간이다. 에폭 타임 이라고도 한다.

 

그리고 자바에서 날짜를 구하는 방법은 Date 클래스를 이용하는 방법인데 날짜끼리의 계산하는 기능이 없어서 사용이 권장되지 않는다.

 

    Date(int year, int month, int day [, int hour, int minute, int second])

    Date(long milliseconds)

 

실제 프로젝트는 Caldendar 클래스의 서브클래스인 GregorianCalendar를 사용한다. 이 클래스는 윤년에 대한 정교한 규칙이 추가되어 있으며 전세계적으로 공인된 태양력을 표현한다.

 

    GregorianCalendar(int year, int month, int day, int hour, int minute, int second)

    GregorianCalendar(TimeZone timezone, Locale locale)

 

그리고 자유로운 형태로 포맷팅을 하려면 날짜 포맷 클래스를 사용한다.

    

    SimpleDateFormat(String pattern)

    String format(Date date)

 

다음은 안드로이드의 날짜 지원 클래스인 SystemClock을 보면

 

    static long elapsedRealtime()

    static long uptimeMillis()

    static long currentThreadTimeMillis()

 

elapsedRealtime은 부팅 후에 경과한 시간을 리턴한다. 절대 시간은 아니지만 작업 경과 시간 등을 계산할 때 편리하게 사용할 수 있다.

uptimeMillis은 부팅 후 경과한 시간을 리턴하지만 장비가 슬립되었을때 시간을 제외한다.

currentThreadTimeMillis는 현재 스레드에서 소비한 시간을 조사한다.

 

실제 사용예제를 봅시다.

xml은 간단히 버튼 한 개와 텍스트뷰 한 개로 구성되어 있습니다.

activity_date_time_test.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    >

<Button

    android:id="@+id/btnrefresh"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:onClick="mOnClick"

    android:text="Refresh"

    />

<TextView

    android:id="@+id/result"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:textSize="16sp"

    android:text=""

    />

</LinearLayout>

 

 

DateTimeTest.Java 파일

 

package com.example.ch13_datetimetest;

 

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.GregorianCalendar;

 

import android.app.Activity;

import android.os.Bundle;

import android.os.SystemClock;

import android.view.View;

import android.widget.TextView;

 

public class DateTimeTest extends Activity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_date_time_test);

        

        Refresh();

    }

 

    public void mOnClick(View v){

        switch(v.getId()){

            case R.id.btnrefresh:

                Refresh();

                break;

        }

    }

    

    void Refresh(){

        StringBuilder time = new StringBuilder();

        

        //에폭타임 구하기

        long epoch = System.currentTimeMillis();

        time.append("epoch = " + epoch + "\n");

        

        //GregorianCalender 이용해서 현재 시간 날짜 구하기

        Calendar cal = new GregorianCalendar();

        time.append("now = " + String.format("%d %d %d %d %d\n",

                cal.get(Calendar.YEAR),

                cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH),

                cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)));

        

        //Date 클래스를 이용한 현재 시간 구하기

        Date now = new Date();

        //SimpleDateFormat 클래스를 사용해서 표시하는 포맷을 바꿔준다.

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");

        time.append("now = " + sdf.format(now) + "\n");

        

        Calendar tom = new GregorianCalendar();

        tom.add(Calendar.DAY_OF_MONTH, 1);//내일날짜를 위해 1일을 더한다.

        

        Date tomdate = tom.getTime();

        //포맷을 바꿔주고

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd");

        //표시해준다.

        time.append("tomorrow = " + sdf2.format(tomdate) + "\n");

        

        //부팅후 경과한시간

        time.append("boot = " + UpTime(SystemClock.elapsedRealtime()));

        //부팅후 경과한시간 슬립시간 제외

        time.append("run = " + UpTime(SystemClock.uptimeMillis()));        

        //현재 쓰레드 사용 시간

        time.append("thread = " + UpTime(SystemClock.currentThreadTimeMillis()));    

        

        TextView result = (TextView)findViewById(R.id.result);

        result.setText(time.toString());

    }

    

    //msec 날짜 형식으로 바꿔주는 메소드

    String UpTime(long msec){

        long sec = msec / 1000;

        

        String result;

        //날짜 형식으로 변환해준다.

        result = String.format("%d %d %d %d\n", sec /86400, sec / 3600 % 24,

                sec / 60 % 60, sec % 60);

        

        return result;

    }

    

}

 

출력 화면

 

반응형