【问题标题】:Convert the string of date and time (2018-04-13T20:00:00.0400) into date string (April 13, 2018) in Kotlin在 Kotlin 中将日期和时间字符串 (2018-04-13T20:00:00.0400) 转换为日期字符串 (April 13, 2018)
【发布时间】:2019-03-16 11:24:36
【问题描述】:

我想将“2018-04-13T20:00:00.0400”之类的 DateTime 字符串转换为“2018 年 4 月 13 日”。我已经使用了代码

val sdf = SimpleDateFormat("yyyy/mm/dd", Locale.getDefault())
val startDate = sdf.parse(data.start_time)

但是使用此代码,我的应用程序崩溃了。有关此的任何帮助

日志显示这个

2018-10-11 16:44:56.948 20482-21021/? E/NowController: Failed to access data from EntryProvider. ExecutionException.
java.util.concurrent.ExecutionException: com.google.android.apps.gsa.sidekick.main.h.n: Could not complete scheduled request to refresh entries. ClientErrorCode: 3
    at com.google.common.util.concurrent.d.eA(SourceFile:85)
    at com.google.common.util.concurrent.d.get(SourceFile:23)
    at com.google.common.util.concurrent.l.get(SourceFile:2)
    at com.google.android.apps.gsa.staticplugins.nowstream.b.a.be.cbB(SourceFile:49)
    at com.google.android.apps.gsa.staticplugins.nowstream.b.a.be.cbA(SourceFile:181)
    at com.google.android.apps.gsa.staticplugins.nowstream.b.a.bh.run(Unknown Source:2)
    at com.google.android.apps.gsa.shared.util.concurrent.at.run(SourceFile:4)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at com.google.android.apps.gsa.shared.util.concurrent.b.g.run(Unknown Source:4)
    at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
    at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:764)
    at com.google.android.apps.gsa.shared.util.concurrent.b.i.run(SourceFile:6)
 Caused by: com.google.android.apps.gsa.sidekick.main.h.n: Could not complete scheduled request to refresh entries. ClientErrorCode: 3
    at com.google.android.apps.gsa.staticplugins.nowstream.b.a.ar.az(Unknown Source:4)
    at com.google.common.util.concurrent.q.ap(SourceFile:7)
    at com.google.common.util.concurrent.p.run(SourceFile:32)
    at com.google.common.util.concurrent.bt.execute(SourceFile:3)
    at com.google.common.util.concurrent.d.b(SourceFile:275)
    at com.google.common.util.concurrent.d.addListener(SourceFile:135)
    at com.google.common.util.concurrent.p.b(SourceFile:3)
    at com.google.android.apps.gsa.shared.util.concurrent.h.a(SourceFile:16)
    at com.google.android.apps.gsa.shared.util.concurrent.h.a(SourceFile:13)
    at com.google.android.apps.gsa.staticplugins.nowstream.b.a.be.cbB(SourceFile:47)

【问题讨论】:

  • 分享你的崩溃日志。
  • @HemantParmar 如何获取崩溃的logcat?
  • 谷歌一下!你会看到很多帖子!
  • 试试这个答案,它会帮助你stackoverflow.com/a/52674753/9185192
  • 仅供参考,java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等麻烦的旧日期时间类现在已被 java.time 类所取代。大多数 java.time 功能在 ThreeTen-Backport 项目中被反向移植到 Java 6 和 Java 7。在ThreeTenABP 项目中进一步适用于早期的Android。见How to use ThreeTenABP…

标签: android datetime exception kotlin runtime-error


【解决方案1】:

Kotlin 语法 LocaleDateTime.parse(示例)=>

val date = LocalDateTime
    .parse(q.ADDDATE)
    .toLocalDate()
    .format(
        DateTimeFormatter
            .ofLocalizedDate(FormatStyle.LONG)
            .withLocale(Locale.ENGLISH)
    )

val dateView = date

【讨论】:

    【解决方案2】:

    tl;博士

    使用现代的 java.time 类,不要使用糟糕的遗留类。

    这里是 Java 语法(我还没有学过 Kotlin)。

    LocalDateTime                             // Represent a date with time-of-day but lacking offset-from-UTC or time zone. As such, this does *not* represent a moment, is *not* a point on the timeline.
    .parse( "2018-04-13T20:00:00.0400" )      // Parse an input string in standard ISO 8601 format. Returns a `LocalDateTime` object.
    .toLocalDate()                            // Extract the date-only portion without the time-of-day. Still no time zone or offset-from-UTC. Returns a `LocalDate` object.
    .format(                                  // Generate text representing the value of that `LocalDate` object.
        DateTimeFormatter                     // Define a pattern to use in generating text.
        .ofLocalizedDate( FormatStyle.LONG )  // Automatically localize, specifying how long/abbreviated…
        .withLocale( Locale.US )              // … and what human language and cultural norms to use in localizing.
    )                                         // Return a `String`. 
    

    2018 年 4 月 13 日

    对于早期的 Android,请参阅下方底部的项目符号。

    使用java.time

    将“2018-04-13T20:00:00.0400”等日期时间字符串转换为“2018 年 4 月 13 日”。

    您正在使用多年前被 java.time 类取代的糟糕的旧日期时间类。

    首先,解析您的输入字符串。但最后那个.0400 是什么?也许是小数秒?但传统上,毫秒、微秒或纳秒以 3 位数字为一组显示。所以你这里的四位数是奇数。也许是UTC的偏移量?四位数是正确的,小时和分钟前导零。但是没有 plusminus 符号来表示在 UTC 之前或之后。所以我会选择小数秒。

    您的输入缺少任何与 UTC 或时区偏移的指标。所以解析为LocalDateTime。您的字符串采用标准 ISO 8601 格式。 java.time 类中默认使用标准格式。

    String input = "2018-04-13T20:00:00.0400";
    LocalDateTime ldt = LocalDateTime.parse( input );
    

    ldt.toString(): 2018-04-13T20:00:00.040

    提取日期部分。

    LocalDate ld = ldt.toLocalDate() :
    

    ld.toString(): 2018-04-13

    生成表示该日期值的文本。让java.time 自动本地化。要进行本地化,请指定:

    • FormatStyle 确定字符串的长度或缩写。
    • Locale 确定:
      • 人类语言用于翻译日名、月名等。
      • 文化规范决定缩写、大写、标点、分隔符等问题。

    代码:

    DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.LONG ).withLocale( Locale.US );
    String output = ld.format( f );
    

    2018 年 4 月 13 日

    注意:LocalDateTime 对象不是片刻,不是时间轴上的一个点。缺少与 UTC 或时区的任何偏移意味着它代表了一系列潜在时刻,沿着大约 26-27 小时的范围(全球当前的时区范围)。如果输入字符串隐含地表示某个区域的挂钟时间中的某个时刻,则应在提取LocalDate 之前应用ZoneId 以获取ZonedDateTime 对象。这已经在 Stack Overflow 上展示过很多次了。


    关于java.time

    java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

    Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

    要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

    您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

    从哪里获得 java.time 类?

    ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

    【讨论】:

      【解决方案3】:

      上述的固定版本,因为您的 Date 输入中没有 Z。而且他们的输出格式与您的不匹配。我建议阅读文档https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html 这样您就可以根据需要修改响应。

      fun convertISOTimeToDate(isoTime: String): String? {
          val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
          var convertedDate: Date? = null
          var formattedDate: String? = null
          try {
              convertedDate = sdf.parse(isoTime)
              formattedDate = SimpleDateFormat("MMMMM dd,yyyy").format(convertedDate)
          } catch (e: ParseException) {
              e.printStackTrace()
          }
      
          return formattedDate
      }
      

      【讨论】:

        【解决方案4】:

        您需要以正确的方式格式化。试试下面的代码,你应该将 ISO 日期格式转换为普通日期格式。谢谢

        fun convertISOTimeToDate(isoTime: String): String? {
                val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                var convertedDate: Date? = null
                var formattedDate: String? = null
                try {
                    convertedDate = sdf.parse(isoTime)
                    formattedDate = SimpleDateFormat("dd-MM-yyyy" + "\n" + " hh:mm:ss a").format(convertedDate)
                } catch (e: ParseException) {
                    e.printStackTrace()
                }
        
                return formattedDate
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-04-09
          • 2018-09-19
          • 2020-03-04
          • 2020-08-04
          • 2011-09-08
          • 1970-01-01
          • 1970-01-01
          • 2021-07-06
          相关资源
          最近更新 更多