Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Lấy thời gian và ngày hiện tại trên Android

Theo tài liệu của Oracle, SimpleDateFormat là một lớp cụ thể để định dạng và phân tích ngày tháng theo cách nhạy cảm với locale. Trong ví dụ này, chúng ta nhập lớp định dạng ngày đơn giản từ Java như sau:

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

Bước 1

Tạo một dự án mới trong Android Studio, vào File → New Project và điền đầy đủ thông tin cần thiết để tạo dự án mới.

Bước 2

Thêm mã sau vào res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"    xmlns:app="https://schemas.android.com/apk/res-auto"    xmlns:tools="https://schemas.android.com/tools"    android:layout_width="match_parent"    android:gravity="center"    android:layout_height="match_parent">    <TextView       android:id="@+id/date"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:layout_centerHorizontal="true"       android:textSize="30sp"       android:layout_marginBottom="36dp" /> </RelativeLayout>

Trong mã trên, chúng ta sử dụng TextView để hiển thị ngày hiện tại trên cửa sổ quản lý.

Bước 3

Thêm mã sau vào src/MainActivity.java

package com.example.andy.myapplication; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity {    @TargetApi(Build.VERSION_CODES.O)    @Override    protected void onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);       setContentView(R.layout.activity_main);       TextView textView=findViewById(R.id.date);       SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");       String currentDateandTime = sdf.format(new Date());       textView.setText(currentDateandTime);    } }

Trong mã trên, chúng ta gọi SimpleDateFormat và từ đó truy xuất ngày hiện tại dưới dạng chuỗi. Có nhiều định dạng ngày khác nhau có sẵn. Tham khảo thêm tại đây.

Bước 4

Không cần thay đổi manifest.xml.

Hãy thử chạy ứng dụng. Giả sử bạn đã kết nối thiết bị Android thực tế với máy tính. Để chạy ứng dụng từ Android Studio, mở một file activity của dự án và nhấn Run từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn và kiểm tra thiết bị sẽ hiển thị màn hình mặc định:

Lấy thời gian và ngày hiện tại trên Android

Trong ví dụ trên, nó hiển thị ngày và giờ hiện tại.