将 yyyy-MM-dd'T'HH:mm:ss.mmm'Z' 转换为正常 "HH:mm a" 格式

Convert yyyy-MM-dd'T'HH:mm:ss.mmm'Z' to normal "HH:mm a" format

我在应用程序中显示日期时遇到问题。

我得到的时间戳为:

2017-08-02T06:05:30.000Z

但是据此 实际时间 是:

2017:08:02 11:35 AM

但在使用我的代码转换后,它显示时间为:

6:00 am

如何显示为当前时间?

我的代码如下:

private static SimpleDateFormat timestampformat = 
                   new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.mmm'Z'");

private static SimpleDateFormat sdftimeformat = new SimpleDateFormat("HH:mm a");

private static SimpleDateFormat getSdftimeformat() {
    return sdftimeformat;
}
public static String timeStampConvertToTime(String time) {
    Date date1 = null;

    try {
        date1 = timestampformat.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formattedTime = getSdftimeformat().format(date1);
    return formattedTime;
}

试试这个你会得到结果

Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd'T'HH:mm:ss'Z'");

                // set your format in df variable

                SimpleDateFormat df = new SimpleDateFormat(
                        "HH:mm a");
                try {
                    cal.setTime('your value');

                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
String localtime = df.format(cal.getTime());

用它来获取当前时间。

  Calendar cal = 
  Calendar.getInstance(TimeZone.getTimeZone("GMT+5:30"));
  Date currentLocalTime = cal.getTime();
  DateFormat date = new SimpleDateFormat("HH:mm a"); 
 // you can get seconds by adding  "...:ss" to it
 date.setTimeZone(TimeZone.getTimeZone("GMT+5:30")); 

 String localTime = date.format(currentLocalTime); 

将时区更改为您所在的时区

您需要使用 SimpleDateFormat class 并指定要解析的格式,如下所示:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());

long timeStamp = sdf.parse('your_timestamp').getTime();

SimpleDateFormat currentDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm a", Locale.getDefault());

String time =currentDateFormat.format(timeStamp); // Formatted time in string form

我假设 Rose 时间戳中的 Z 是祖鲁时间,硬编码从祖鲁时间到他本地时区的转换是不正确的(我们假设是 GMT+5:30)。如果它总是返回 Z 可能没问题,但如果它是 military time zones 您需要能够处理所有可能时区的东西。

This previous question 意味着没有内置的方法来做到这一点。需要了解时间戳的来源才能真正回答问题。

首先,您在格式中使用了 mm:ss.mmm。根据SimpleDateFormat javadocm代表分钟,所以你必须把它改成mm:ss.SSS,因为S代表毫秒。

另一个细节是最后的Ztimezone designator for UTC,不能忽略(至少不应该)。您必须为此使用相应的模式,即 X:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date = sdf.parse("2017-08-02T06:05:30.000Z");

PS: X 模式在 Java 7 中引入。如果您使用 Java <= 6,唯一的选择是将 Z 视为文字(我承认这是一个丑陋的解决方法)并将 UTC 设置为解析器使用的时区:

// treat "Z" as literal
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// use UTC as timezone
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2017-08-02T06:05:30.000Z");

有了这个,日期将具有对应于 UTC 中的 06:05 的值。要将时间格式化为您的时区,您必须使用另一个具有相应时区的 SimpleDateFormat

// output format: hour:minute AM/PM
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
// assuming a timezone in India
outputFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
System.out.println(outputFormat.format(date));

输出将是:

11:35 AM

如果您不设置时区,它将使用系统的默认值。但是默认值可以在没有通知的情况下更改,即使在运行时也是如此,所以最好像上面那样明确设置一个特定的时区。

我还使用 java.util.Locale 将语言设置为英语,因为某些语言环境可以为 AM/PM 使用不同的符号。如果您不指定一个,它将使用系统默认值,并且不能保证是您需要的符号(某些语言环境使用 "a.m./p.m." 或其他不同的格式,因此最好使用明确的语言环境)。


Java 新 Date/Time API

旧的 classes(DateCalendarSimpleDateFormat)有 lots of problems and design issues,它们正在被新的 APIs.

如果您正在使用 Java 8,请考虑使用 new java.time API. It's easier, less bugged and less error-prone than the old APIs.

如果您使用 Java <= 7,您可以使用 ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it ).

下面的代码适用于两者。 唯一的区别是包名称(在 Java 8 中是 java.time,在 ThreeTen Backport(或 Android 的 ThreeTenABP)中是 org.threeten.bp),但是 classes 和方法 names 相同。

要解析输入,您可以使用 ZonedDateTime class,它完全支持时区,并且可以很容易地转换到另一个时区。然后你使用 DateTimeFormatter 格式化输出:

// parse the input
ZonedDateTime parsed = ZonedDateTime.parse("2017-08-02T06:05:30.000Z");
// convert to another timezone
ZonedDateTime z = parsed.withZoneSameInstant(ZoneId.of("Asia/Kolkata"));
// format output
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
System.out.println(fmt.format(z));

输出将是:

11:35 AM

如果输入总是最后有Z,也可以用Instant class:

// parse the input
Instant instant = Instant.parse("2017-08-02T06:05:30.000Z");
// convert to a timezone
ZonedDateTime z = instant.atZone(ZoneId.of("Asia/Kolkata"));

请注意,我在小时数中使用了 hh:这将使用 1 到 12 之间的值进行格式化(这是有道理的,因为我还使用了 AM/PM 指示符)。如果您想要 0 到 23 之间的值,请改用 HH - 查看 javadoc 了解更多详情。

另请注意 API 使用 IANA timezones names(始终采用 Region/City 格式,如 Asia/KolkataEurope/Berlin)。 避免使用 3 个字母的缩写(如 CSTIST),因为它们是 ambiguous and not standard.

您可以通过调用 ZoneId.getAvailableZoneIds().

获取可用时区列表(并选择最适合您的系统的时区)

您还可以将系统的默认时区与 ZoneId.systemDefault() 一起使用,但这可以在不通知的情况下更改,即使在运行时也是如此,因此最好明确使用特定的时区。