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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45452791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:41:54  来源:igfitidea点击:

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

javaandroiddatetimetimestampsimpledateformat

提问by Rose

I have a problem in displaying the date in my Application.

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

I am getting timestamp as:

我得到的时间戳为:

2017-08-02T06:05:30.000Z

2017-08-02T06:05:30.000Z

But as per this the actual timeis:

但按照这个实际时间是:

2017:08:02 11:35 AM

2017:08:02 上午 11:35

But after converting using my code it displays the time as:

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

6:00 am

上午6:00

How to show it as current time?

如何将其显示为当前时间?

My code is given below:

我的代码如下:

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;
}

回答by

The first thing is that you're using mm:ss.mmmin your format. According to SimpleDateFormatjavadoc, mrepresents the minutes, so you must change it to mm:ss.SSSbecause Srepresents the milliseconds.

第一件事是您正在使用mm:ss.mmm您的格式。根据SimpleDateFormatjavadocm代表分钟,所以你必须把它改成mm:ss.SSS因为S代表毫秒。

Another detail is that the Zin the end is the timezone designator for UTCand it can't be ignored (at least it shouldn't). You must use the corresponding pattern for that, which is X:

另一个细节是Z最后是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:the Xpattern was introduced in Java 7. If you're using Java <= 6, the only alternative is to treat Zas a literal (an ugly workaround, I admit) and set the UTC as the timezone used by the parser:

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");

With this, the date will have the value corresponding to 06:05 in UTC. To format the time to your timezone, you must use another SimpleDateFormatwith the corresponding timezone:

这样,日期的值将对应于 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));

The output will be:

输出将是:

11:35 AM

上午 11:35

If you don't set a timezone, it'll use the system's default. But the default can be changed without notice, even at runtime, so it's better to explicity set a specific timezone as above.

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

I also used java.util.Localeto set the language to English, because some locales can have different symbols for AM/PM. If you don't specify one, it'll use the system default and it's not guaranteed to be one in which the symbols are the ones you need (some locales uses "a.m./p.m." or another different formats, so it's better to use an explicit locale).

我也曾经java.util.Locale将语言设置为英语,因为某些语言环境可以有不同的 AM/PM 符号。如果您不指定,它将使用系统默认值,并且不能保证是您需要的符号(某些语言环境使用“am/pm”或其他不同格式,因此最好使用显式语言环境)。



Java new Date/Time API

Java 新的日期/时间 API

The old classes (Date, Calendarand SimpleDateFormat) have lots of problemsand design issues, and they're being replaced by the new APIs.

旧类(Date,CalendarSimpleDateFormat)有很多问题设计问题,它们正在被新的 API 取代。

If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

如果您使用的是Java 8,请考虑使用新的 java.time API与旧的 API 相比,它更容易、更少被窃听且更不容易出错

If you're using Java <= 7, you can use the 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 here).

如果您使用的是Java <= 7,则可以使用ThreeTen Backport,这是 Java 8 新日期/时间类的一个很好的向后移植。对于Android,有ThreeTenABP(更多关于如何使用它在这里)。

The code below works for both. The only difference is the package names (in Java 8 is java.timeand in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods namesare the same.

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

To parse the input you can use the ZonedDateTimeclass, which has full support to timezones and it makes the conversion to another zones very easy. Then you use a DateTimeFormatterto format the output:

要解析输入,您可以使用ZonedDateTime该类,该类完全支持时区,并且可以非常轻松地转换到另一个时区。然后使用 aDateTimeFormatter来格式化输出:

// 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));

The output will be:

输出将是:

11:35 AM

上午 11:35

If the input alwayshas Zin the end, you can also use the Instantclass:

如果输入总是Z在最后,你还可以使用Instant类:

// 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"));

Note that I used hhfor the hours: this will format using values from 1 to 12 (it makes sense because I'm also using the AM/PM designators). If you want values from 0 to 23, use HHinstead - check the javadocfor more details.

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

Also note that the API uses IANA timezones names(always in the format Region/City, like Asia/Kolkataor Europe/Berlin). Avoid using the 3-letter abbreviations (like CSTor IST) because they are ambiguous and not standard.

还要注意的是,API使用IANA时区的名称(总是在格式Region/City,如Asia/KolkataEurope/Berlin)。避免使用 3 个字母的缩写(如CSTIST),因为它们含糊不清且不标准

You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().

您可以通过调用获取可用时区列表(并选择最适合您系统的时区)ZoneId.getAvailableZoneIds()

You can also use the system's default timezone with ZoneId.systemDefault(), but this can be changed without notice, even at runtime, so it's better to explicity use a specific one.

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

回答by Saurabh Padwekar

You need to use SimpleDateFormat class and specify the format you want to parse from , like this :

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

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

回答by Steve Bauer

I assume the Z in Rose's timestamp is zulu time, it isn't really correct to hard code the conversion from zulu time to his local time zone (GMT+5:30 we are assuming). It might be OK if it is always returning Z but if it is military time zonesyou would need something that can handle all the possible timezones.

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

This previous questionimplies there is no built in way to do it. Need to understand where the timestamp is coming from to really answer the question.

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

回答by PCGALI ANDROID

try this your will get result

试试这个你会得到结果

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());

回答by Mahesh Gawhane

use this for get current time.

使用它来获取当前时间。

  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); 

change time zone to your time zone

将时区更改为您的时区