如何在 Android 中將毫秒轉換為日期格式?


本示例演示如何在 Android 中將毫秒轉換為日期格式。

步驟 1 − 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新專案並填寫所有必需詳細資訊以建立一個新專案。

步驟 2 − 將以下程式碼新增到 res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:padding="4dp"
   tools:context=".MainActivity">
   <TextView
      android:textStyle="bold"
      android:textSize="24sp"
      android:id="@+id/textView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>
</LinearLayout>

步驟 3 − 將以下程式碼新增到 src/MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.SimpleDateFormat;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.textView);
      getDate();
   }
   private void getDate() {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
      String dateString = simpleDateFormat.format(9897546853323L);
      textView.setText(String.format("Date: %s", dateString));
   }
}

步驟 4 − 將以下程式碼新增到 androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://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>

讓我們嘗試執行你的應用程式。我假設您已將您的 Android 移動裝置與您的電腦連線。要從 Android Studio 執行該應用,請開啟您的一個專案的活動檔案並點選執行  工具欄中的圖示。選擇您的移動裝置作為選項,然後檢視將顯示預設螢幕的移動裝置 −

單擊 此處 下載專案程式碼。

更新於: 2019 年 11 月 15 日

2K+ 瀏覽量

開啟您的 職業

完成課程,獲得認證

開始
廣告