DJ2*_*DJ2 2 android kotlin android-studio
我正在尝试将UTC字符串日期转换为本地时间,因此采用了更具可读性的格式。textView我的活动布局中有一个:
<TextView
android:id="@+id/dateTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/titleTv"
tools:text="Published Date" />
Run Code Online (Sandbox Code Playgroud)
在我的活动中:
class FullArticleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_full_article)
val articleJson = intent.getStringExtra(ARTICLE_KEY)
if(!articleJson.isNullOrBlank()) {
val article = Gson().fromJson<Article>(articleJson, Article::class.java)
val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ", Locale.getDefault())
formatter.timeZone = TimeZone.getTimeZone("UTC")
val formattedDate = formatter.parse(article.publishedAt)
titleTv.text = article.title
//UTC string
dateTv.text = article.publishedAt
contentTv.text = article.content
Run Code Online (Sandbox Code Playgroud)
该publishedAt字符串是从API调用此格式"2018-12-10T19:48:39Z"。如何将ZULU时间格式转换为本地时间?
尝试使用扩展功能
fun String.toDate(dateFormat: String = "yyyy-MM-dd HH:mm:ss", timeZone: TimeZone = TimeZone.getTimeZone("UTC")): Date {
val parser = SimpleDateFormat(dateFormat, Locale.getDefault())
parser.timeZone = timeZone
return parser.parse(this)
}
fun Date.formatTo(dateFormat: String, timeZone: TimeZone = TimeZone.getDefault()): String {
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
formatter.timeZone = timeZone
return formatter.format(this)
}
Run Code Online (Sandbox Code Playgroud)
用法:
"2018-09-10 22:01:00".toDate().formatTo("dd MMM yyyy")
Run Code Online (Sandbox Code Playgroud)
输出:“ 2018年9月11日”
| 归档时间: |
|
| 查看次数: |
3316 次 |
| 最近记录: |