将日期/时间解析为本地时区

时间:2018-07-06 08:50:46

标签: android date try-catch java-date

我正在尝试从服务器内部绑定viewholder中解析日期/时间json。 要解析的日期字符串是这样的:

2018-06-25T08:06:52Z

这是我正在使用的代码(是从另一个堆栈溢出线程获得的)

  try {


           SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
           df.setTimeZone(TimeZone.getTimeZone("Africa/Nairobi"));
           Date date = df.parse(timeToConvert);
           df.setTimeZone(TimeZone.getDefault());
           String formattedDate = df.format(date);
           String trimmed = formattedDate.substring(11,16);
           myViewHolder.date_TV.setText(trimmed);

       }catch (Exception e){

       }

但是这不起作用,设置为文本视图的时间与解析之前的时间相同。

2 个答案:

答案 0 :(得分:1)

  

设置为文本视图的时间与解析之前的时间相同。

这是因为您没有传递新的SimpleDateFormat

尝试一下:

final String serverDate = "2018-06-25T08:06:52Z"
final SimpleDateFormat serverDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
final SimpleDateFormat yourDateFormat = new SimpleDateFormat("yyyy-MM-dd"); // put whatever you want here!

try {
    final Date date = serverDate.parse(serverDateFormat);
    final String formattedDate = yourDateFormat.format(date);
} catch (ParseException e) {
    System.out.println(e.toString());
}

这样,您将服务器格式的String解释为纯Date对象。然后,您可以随心所欲地对该对象进行任何操作,然后将其转换为所需的任何格式(通过提供新格式)。

有关构建日期格式模式的更多信息,请参见this link

答案 1 :(得分:1)

    String timeToConvert = "2018-06-25T08:06:52Z";
    Instant inst = Instant.parse(timeToConvert);
    LocalTime time = inst.atZone(ZoneId.of("Africa/Nairobi"))
            .toLocalTime()
            .truncatedTo(ChronoUnit.MINUTES);
    System.out.println("Time in Nairobi: " + time);

此打印:

  

内罗毕时间:11:06

我正在使用java.time,在这种情况下,该端口是Java 6和7的反向端口。该反向端口在Android版本中也可用,您可以将其用于较低的Android API级别。我的进口是:

import org.threeten.bp.Instant;
import org.threeten.bp.LocalTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.temporal.ChronoUnit;

如果您需要使用这种格式的API的时间字符串,则可以。如果您要在显示给用户的时间字符串之后,请考虑改用Java的内置格式:

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
    ZonedDateTime dateTime = inst.atZone(ZoneId.of("Africa/Nairobi"));
    System.out.println("Formatted: " + dateTime.format(timeFormatter));

我尝试在斯瓦希里语(sw_KE)语言环境中运行此命令,并得到:

  

格式化:上午11:06

显然,此语言环境使用英语AM / PM表示时间的方式(在Kikuyu和Kalenjin语言环境中,我得到了相同的结果)。在英国语言环境中,我得到的格式与以前相同:

  

格式化:11:06

我正在使用并建议使用java.time(现代Java日期和时间API)。对于阅读并使用Java 8或更高版本或针对Android API级别26或更高版本进行编程的任何人,您都不需要提及的反向端口。只需使用子包而不是上述包从java.time导入内置的日期时间类即可。

您的代码出了什么问题?

您的错误来自将日期时间字符串中的Z硬编码为文字。它的UTC偏移量为零,当您不这样解析时,日期时间字符串将在您的SimpleDateFormat(非洲/内罗毕)的时区中进行解析,这对于您的字符串是不正确的。< / p>

恕我直言,您根本不需要使用SimpleDateFormatTimeZoneDate。这些课程早已过时,特别是第一个已证明很麻烦。我总是改用java.time

另一个提示:不要吞下例外。不要将您的catch块留空。以某种明显的方式报告异常。这是您发现代码中何时出问题的机会。

链接