Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีแปลงมิลลิวินาทีเป็นรูปแบบวันที่ใน Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการแปลงค่ามิลลิวินาที (Milliseconds) ให้เป็นรูปแบบวันที่ที่อ่านง่ายใน Android โดยใช้ SimpleDateFormat และ Kotlin

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="@android:color/holo_orange_dark"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity.kt

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.text.SimpleDateFormat
import java.util.Locale

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val textView: TextView = findViewById(R.id.textView)
        val simpleDateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
        val dateString = simpleDateFormat.format(9897546853323L)
        textView.text = "Date: $dateString"
    }
}

ขั้นตอนที่ 4: ตั้งค่า AndroidManifest.xml

ใช้การตั้งค่ามาตรฐาน

ทดสอบการทำงาน

รันแอปจะแสดงวันที่ที่แปลงจากค่ามิลลิวินาทีตัวอย่าง (9897546853323L)

ข้อมูลเพิ่มเติม

  • รูปแบบวันที่ทั่วไป: "dd/MM/yyyy", "yyyy-MM-dd", "MMM dd, yyyy"
  • รวมเวลา: "dd/MM/yyyy HH:mm:ss"
  • ใช้ Locale: ระบุ Locale เพื่อรองรับภาษา/ภูมิภาคต่างๆ
  • API ใหม่: Android 8.0+ แนะนำใช้ java.time package (Instant, DateTimeFormatter) แทน SimpleDateFormat