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

Cách tính khoảng cách giữa hai ngày trong Android

Giới thiệu

Ví dụ này minh họa cách tính số ngày chênh lệch giữa hai ngày (date) trong Android sử dụng SimpleDateFormat và Date.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:textSize="16sp"
        android:textStyle="bold|italic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
</RelativeLayout>

Bước 3: Code tính toán (MainActivity.java)

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        textView = findViewById(R.id.textView);
        
        try {
            String currentDate = "09/24/2018";
            String finalDate = "09/26/2019";
            Date date1, date2;
            SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
            
            date1 = dates.parse(currentDate);
            date2 = dates.parse(finalDate);
            
            long difference = Math.abs(date1.getTime() - date2.getTime());
            long differenceDates = difference / (24 * 60 * 60 * 1000);
            String dayDifference = Long.toString(differenceDates);
            
            textView.setText("Khoảng cách giữa hai ngày là " + dayDifference + " ngày");
        } catch (Exception exception) {
            Toast.makeText(this, "Không thể tính khoảng cách", Toast.LENGTH_SHORT).show();
        }
    }
}

Bước 4: Manifest (AndroidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run để xem kết quả tính khoảng cách ngày.

Cách tính khoảng cách giữa hai ngày trong Android

Lưu ý hiện đại: Từ API 26, nên dùng java.time.LocalDate và ChronoUnit.DAYS.between() cho chính xác và an toàn luồng hơn.