在Android中的日期格式问题

huangapple go评论109阅读模式
英文:

Date formatting issue in Android

问题

我在将字符串转换为日期时遇到了问题。27-Jul-2020 是我日期的输入字符串。

  1. SimpleDateFormat inputFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
  2. Date parsedTransactionDate = inputFormat.parse(transactionDate);// 交易日期是 `27-Jul-2020`

它返回的输出是 Sun Jul 27 00:00:00 GMT+05:30 2020
我无法确定问题所在。

英文:

I am facing an issue while converting String to date. 27-Jul-2020 this is my input String for the date.

  1. SimpleDateFormat inputFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
  2. Date parsedTransactionDate = inputFormat.parse(transactionDate);//transaction date is `27-Jul-2020`

It's returing me output Sun Jul 27 00:00:00 GMT+05:30 2020.
I'm unable to identify the issue

答案1

得分: 1

如果您只想获取日期,那么很遗憾,java.util.Date 不是一个好的选择。该API已经过时,因此我建议切换到 java.time。使用 java.time.LocalDatejava.time.format.DateTimeFormatter,这是一种方便且灵活的方式:

  1. public static void main(String[] args) {
  2. // 为解析提供一个格式化器
  3. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH);
  4. // 使用该格式化器解析示例字符串
  5. LocalDate parsedTransactionDate = LocalDate.parse("27-Jul-2020", formatter);
  6. // 打印LocalDate的默认格式
  7. System.out.println(parsedTransactionDate);
  8. // 或使用上面定义的格式化器打印它
  9. System.out.println(parsedTransactionDate.format(formatter));
  10. // 或使用具有不同区域设置的完全不同格式化器进行打印
  11. System.out.println(parsedTransactionDate.format(
  12. DateTimeFormatter.ofPattern("EEEE, dd 'de' MMMM uuuu", Locale.FRENCH))
  13. );
  14. }

输出结果如下:

  1. 2020-07-27
  2. 27-Jul-2020
  3. lundi, 27 de juillet 2020
英文:

If you want just a date, then, unfortunately, java.util.Date is not a good choice. That API is outdated anyway, so I suggest switching to java.time. Use java.time.LocalDate and a java.time.format.DateTimeFormatter, it's a handy and flexible way:

  1. public static void main(String[] args) {
  2. // provide a formatter for parsing
  3. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH);
  4. // parse the example String using that formatter
  5. LocalDate parsedTransactionDate = LocalDate.parse("27-Jul-2020", formatter);
  6. // print the default format of a LocalDate
  7. System.out.println(parsedTransactionDate);
  8. // or print it using the formatter defined above
  9. System.out.println(parsedTransactionDate.format(formatter));
  10. // or print it using a totally different formatter with a different locale
  11. System.out.println(parsedTransactionDate.format(
  12. DateTimeFormatter.ofPattern("EEEE, dd 'de' MMMM uuuu", Locale.FRENCH))
  13. );
  14. }

the output is this

  1. 2020-07-27
  2. 27-Jul-2020
  3. lundi, 27 de juillet 2020

huangapple
  • 本文由 发表于 2020年8月4日 17:27:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63243904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定