如何在 Android 中将 ISO 8601 字符串转换为日期/时间对象?
此示例演示如何将 ISO 8601 字符串转换为 Android 中的日期/时间对象。
步骤 1 − 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新建项目并填写所有必需的详细信息以创建新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:gravity="center" tools:context=".MainActivity"> <TextView android:padding="20sp" android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="12sp" android:textStyle="bold"/> </RelativeLayout>
步骤 3 − 将以下代码添加到 src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.ParseException;
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);
String dtStart = "2019-08-15T09:27:37Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dtStart);
textView.setText("ISO 1801 date/time: " + date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}步骤 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 运行应用,打开项目的一个活动文件,然后单击工具栏中的运行
图标。将你的移动设备选择为一个选项,然后检查会显示默认界面的移动设备 -

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP