[안드로이드] 현재 시간, 현재 날짜 구하기 (SimpleDateFormat)

Android 현재 시간, 현재 날짜 구하기

SimpleDateFormat

Preview
  • Step1. 현재 시간 가져오기.

    • long now = System.currentTimeMillis();
  • Step2. Date 생성하기

    • Date date = new Date(now);
  • Step3. 가져오고 싶은 형식으로 가져오기

    • SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd”);

    • String getTime = sdf.format(date);


Result


MainActivity.java


package charlie.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    long mNow;
    Date mDate;
    SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    TextView mTextView;
    Button mRefreshBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //bind view
        mTextView = (TextView) findViewById(R.id.textView);
        mRefreshBtn = (Button) findViewById(R.id.refreshBtn);

        //bind listener
        mRefreshBtn.setOnClickListener(this);
    }

    private String getTime(){
        mNow = System.currentTimeMillis();
        mDate = new Date(mNow);
        return mFormat.format(mDate);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.refreshBtn:
                mTextView.setText(getTime());
                break;
            default:
                break;
        }
    }
}


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context="charlie.myapplication.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="18sp"
        android:layout_marginBottom="14dp"
        />
    <Button
        android:id="@+id/refreshBtn"
        android:text="refresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>