尝试使用 SimpleDateFormat Class 使用 android kotlin 格式化 Unix 日期模式 (%Y-%m-%d) 但没有结果

Try to format a Unix date pattern (%Y-%m-%d) with android kotlin using SimpleDateFormat Class but no result

我从 API 收到那个日期模式,我正在尝试用我的 android 应用程序解析它,但不知道如何做,我们将不胜感激。

我已经尝试了一堆日期库并花了很多时间进行研究但没有结果。

And here is simple of the code i am trying :

val simpleFormat = SimpleDateFormat("%Y-%m-%d", Locale.getDefault())
simpleFormat.timeZone = TimeZone.getDefault()
val now: Calendar = Calendar.getInstance()!!

Log.d("datedate", simpleFormat.format(now.time).toString())

我收到以下结果 %2019-%20-%25

我正在寻找一个正常的日期,例如2019-4-25

从日期格式化程序代码中删除 % 符号或将其更改为以下代码。它应该正确显示日期。

val simpleFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

在 SimpleDateFormat 中,您可以指定日期的输出方式。

在你的例子中你有 %Y-%M-%d 所以你会得到 %2019-%01-%01

如果您更改为 Y-M-d,您将得到 2019-01-01

在你的代码中

val simpleFormat = SimpleDateFormat("Y-m-d", Locale.getDefault())

您可以查看 Documentation 了解更多信息

Unix 日期格式字符串,例如您的 %Y-%m-%d,遵循与 Java 的 DateTimeFormatter 或麻烦且过时的 [=] 所使用的格式模式字符串完全不同的系统13=],例如 yyyy-MM-dd(另一方面,两个 Java 类 使用非常相似,但不完全相同的格式模式字符串)。

我认为您需要决定的第一件事是要涵盖所有可能的 Unix 格式字符串还是只涵盖最常见的字符串。 Unix 格式字符串语言非常复杂。很容易将 运行 变成 %Yyyyy%m 变成 MM,等等,%% 变成一个 %.您需要将前面没有百分号的任何字母用单引号括起来,以告诉 Java 格式化程序它们不是模式字母。例如 Unix %d of %B 在 Java 中应该是 dd 'of' MMMM。 Unix 还包括世纪的 %C,Java 不支持(或者仅通过 DateTimeFormatterBuilder 和自制的 TemporalField,你不会想打扰)。 POSIX有一些三个字符的扩展名,%Ec%EC%Ex等,您可以插入_-0 在百分号和控制填充的字母之间。最后,GNU 和 BSD 之间存在差异,因此您需要根据自己的情况来决定。

对于从 Unix 到 Java 的 t运行,您可能会使用正则表达式走很长一段路,但如果您确实想涵盖所有情况,我希望手动编写解析器代码会在长 运行.

中更容易

黑客:String.format

String.format in Java 使用的格式字符串有点类似于 Unix date 使用的格式字符串。主要区别在于 Java 在百分号和字母之间有一个 t:Unix 中的 %Y 在 Java 中是 %tY,等等。所以插入一个:

    String unixFormatString = "%Y-%m-%d";
    // Insert 't'
    String javaFormatString = unixFormatString.replaceAll("(%)(\w)", "t");

    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Antarctica/Rothera"));

    // We need to pass the datetime to String.format as many times as there are
    // format specifiers in the format string. There cannot be more than half of the
    // length of the string. Passing too many doesn’t harm, so just pass this many.
    Object[] formatArgs = Collections.nCopies(javaFormatString.length() / 2, now).toArray();
    String formattedDateTime = String.format(javaFormatString, formatArgs);
    System.out.println(formattedDateTime);

当我今天 运行 这个片段时,我得到:

2019-01-26

它没有涵盖很多情况,但涵盖了许多最常见的情况。

Link

How To Format Date For Display or Use In a Shell Script