2019/05/10

[Android] Get Current Time

從系統直接抓時間資訊,包含秒、分、時、日期、年份...等


抓系統時間的寫法:
Calendar now = Calendar.getInstance();

設定顯示的格式
DateFormat timeFormat = new SimpleDateFormat("H:mm a");
String time = timeFormat .format(now.getTime());
DateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyy");
String date = dateFormat.format(now.getTime());

如果要更改時間 (ex.加30分鐘)
now.add(Calendar.MINUTE, 31);
String time = timeFormat .format(now.getTime());


再利用計時器每秒更新時間:
private Runnable timeTask = new Runnable() {
    @Override
    public void run() {
        now = Calendar.getInstance();
        timeStr = timeFormat.format(now.getTime());
        dateStr = dateFormat.format(now.getTime());
        tv_currentTime.setText(timeStr);
        tv_currentDate.setText(dateStr);

        timeHandler.postDelayed(timeTask, 1000);
    }
};


完整程式碼 MainActivity.java:
public class MainActivity extends AppCompatActivity {
    private String timeStr, dateStr;
    private TextView tv_currentTime, tv_currentDate;
    private Calendar now;
    private DateFormat timeFormat, dateFormat;
    private Handler timeHandler;

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

        tv_currentTime = findViewById(R.id.id_tv_CurrentTime);
        tv_currentDate = findViewById(R.id.id_tv_CurrentDate);

        now = Calendar.getInstance();
        timeFormat = new SimpleDateFormat("h:mm a");
        dateFormat = new SimpleDateFormat("EEE, MMM d, yyyy");
        timeStr = timeFormat.format(now.getTime());
        dateStr = dateFormat.format(now.getTime());
        tv_currentTime.setText(timeStr);
        tv_currentDate.setText(dateStr);

        timeHandler = new Handler();
        timeHandler.postDelayed(timeTask, 1000);
    }

    protected void onDestroy() {
        super.onDestroy();
        timeHandler.removeCallbacks(timeTask);
    }

    private Runnable timeTask = new Runnable() {
        @Override
        public void run() {
            now = Calendar.getInstance();
            timeStr = timeFormat.format(now.getTime());
            dateStr = dateFormat.format(now.getTime());
            tv_currentTime.setText(timeStr);
            tv_currentDate.setText(dateStr);
            timeHandler.postDelayed(timeTask, 500);
        }
    };
}
END

沒有留言:

張貼留言