Here my code

    val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
    val mDate = formatter.parse(dateString)
    val date = SimpleDateFormat("EEEE, MMMM d, yyyy", Locale.getDefault())
    date.timeZone = TimeZone.getTimeZone("UTC")
    return (date.format(mDate))

谁能给我指出正确的方向来解析这个日期字符串?

最好的考虑。

2 个评论
你的代码对我来说运行良好。试着用Locale.ENGLISH来表示格式化,这可能会有不同的效果。
谢谢你的回答,我又检查了一次我的代码,我忘了把我的旧格式 "yyyy-MM-dd'T'HH:mm:ss'Z'"改为 "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"。(提供的代码是一个以格式为参数的函数。再次感谢你,对不起 !
android
date
kotlin
kirusamma
kirusamma
发布于 2020-10-13
2 个回答
Arvind Kumar Avinash
Arvind Kumar Avinash
发布于 2020-10-13
已采纳
0 人赞同

替换代码0】的日期时间类已经过时且容易出错,其格式化API也是如此,SimpleDateFormat。我建议你应该完全停止使用它们,改用现代日期-时间API.

如果你正在为你的安卓项目做这件事,而你的安卓API级别仍然不符合Java-8的要求,请检查通过解ugaring提供的Java 8+ APIs如何在Android项目中使用ThreeTenABP.

Learn more about the 现代日期-时间API at 路径:日期 时间.

Using the 现代日期-时间API:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
    public static void main(String[] args) {
        System.out.println(formatDateStr("2020-09-23T13:45:13.371Z"));
    static String formatDateStr(String strDate) {
        return OffsetDateTime.parse(strDate).format(DateTimeFormatter.ofPattern("EEEE, MMMM d, uuuu", Locale.ENGLISH));

Output:

Wednesday, September 23, 2020

使用传统的API。

Note that Z in the date-time stands for Zulu time (0-hour offset)和therefore make sure to set the time-zone to UTC.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
    public static void main(String[] args) throws ParseException {
        System.out.println(formatDateStr("2020-09-23T13:45:13.371Z"));
    static String formatDateStr(String strDate) throws ParseException {
        DateFormat inputFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        inputFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        DateFormat outputFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy", Locale.ENGLISH);
        return outputFormatter.format(inputFormatter.parse(strDate));

Output:

Wednesday, September 23, 2020
    
nidhal belhadj salem
nidhal belhadj salem
发布于 2020-10-13
0 人赞同

你可以使用本地的SimpleDateFromat来解析这种日期。

String yourTime = "2020-09-23T13:45:13.371Z";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {
        calendar.setTime(sdf.parse(yourTime));
    } catch (ParseException e) {