2023-06-01

【Kotlin】計算起、迄時刻所經歷的時間

app 層級 build.gradle

 
android {
    ...
    ...
    
    buildFeatures {
        viewBinding true
    }
}
 



activity_main.xml
 
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtHello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:onClick="timeDuration"
        />

</androidx.constraintlayout.widget.ConstraintLayout>
 



MainActivity.kt
 
package 完整package名

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.SystemClock
import android.view.View
import com.example.timeduration.databinding.ActivityMainBinding
import java.util.Date


class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
    }

    fun timeDuration(vv: View) {
        // 狀況 1: 變數型態為 Date 類別
        val a1 = Date()
        SystemClock.sleep(123)
        val a2 = Date()

        // 狀況 2: 變數型態為字串, 則轉換為 Date 類別
        /*
        val pattern = "yyyy.MM.dd HH:mm:ss.SSS"
        val formatter = SimpleDateFormat(pattern, Locale.getDefault())
        val a1 = formatter.parse("2023.05.01 00:00:00.000")
        val a2 = formatter.parse("2023.05.01 01:10:11.123")
        */

        val durationMillis = a2.time - a1.time

        // 精確度達 0.001 秒
        val hours = durationMillis / (1000 * 60 * 60)
        val minutes = durationMillis % (1000 * 60 * 60) / (1000 * 60)
        val seconds = durationMillis % (1000 * 60) / 1000
        val millis = durationMillis % 1000

        // 輸出格式為  時:分:秒.毫秒
        val sDuration = String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, millis)
        binding.txtHello.text = sDuration
    }
}
 



沒有留言:

張貼留言