我有这个日期“08/08/2019”,我希望它看起来像这样:“2019 年 8 月 8 日”,我尝试使用when
但想知道是否有更简单的方法可以做到这一点?我知道这是一个小问题,但我试图通过互联网找到答案,但我找不到。
问问题
4776 次
3 回答
5
首先,您需要将字符串转换为 Date 对象,然后使用新的java.time将其转换为您的格式
更新
val firstDate = "08/08/2019"
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy")
val date = formatter.parse(firstDate)
val desiredFormat = DateTimeFormatter.ofPattern("dd, MMM yyyy").format(date)
println(desiredFormat) //08, Aug 2019
旧答案
val firstDate = "08/08/2019"
val formatter = SimpleDateFormat("dd/MM/yyyy")
val date = formatter.parse(firstDate)
val desiredFormat = SimpleDateFormat("dd, MMM yyyy").format(date)
println(desiredFormat) //08, Aug 2019
于 2019-05-19T11:17:37.783 回答
1
使用预定义的本地化格式和 java.time
Locale englishIsrael = Locale.forLanguageTag("en-IL");
DateTimeFormatter shortDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(englishIsrael);
DateTimeFormatter mediumDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(englishIsrael);
String dateStringWeHave = "08/08/2019";
LocalDate date = LocalDate.parse(dateStringWeHave, shortDateFormatter);
String dateStringWeWant = date.format(mediumDateFormatter);
System.out.println(dateStringWeWant);
对 Java 语法感到抱歉,我相信你会翻译。输出是:
2019 年 8 月 8 日
这不完全08, Aug 2019
是你要求的。但是,Java 通常对全球人们期望的格式有一个很好的了解,所以我的第一个建议是你考虑解决这个问题(坦率地说08
,逗号对我来说也有点奇怪,但我知道什么?)
代码片段演示的另一个功能是使用LocalDate
和DateTimeFormatter
来自 java.time,现代 Java 日期和时间 API。我强烈推荐 java.time 超过长期过时的日期时间类Date
,尤其是SimpleDateFormat
. 他们设计得很糟糕。他们被替换是有原因的。
如果您的用户说他们绝对想要08, Aug 2019
,您需要通过格式模式字符串指定:
DateTimeFormatter handBuiltFormatter = DateTimeFormatter.ofPattern("dd, MMM uuuu", englishIsrael);
String dateStringWeWant = date.format(handBuiltFormatter);
现在我们确实得到了您要求的输出:
2019 年 8 月 8 日
链接: Oracle 教程:解释如何使用现代 Java 日期和时间 API java.time 的日期时间。
于 2019-05-20T16:03:02.963 回答
0
您可以使用 Java 的 SimpleDataFormat 类:
import java.text.SimpleDateFormat
在您的代码中的某处:
val myDateStr = "08/08/2019"
val parsedDateObj = SimpleDateFromat("dd/MM/yyyy").parse(myDateStr)
val formattedDateStr = SimpleDateFormat("dd, MMM yyyy").format(parsedDateObj) // "08, Aug 2019"
于 2019-05-19T11:10:13.793 回答