当前位置: 首页 > 知识库问答 >
问题:

Kotlin LocalDateTime为长[重复]

郎宣
2023-03-14

我正在尝试将LocalDateTime字段保存为long,以便将其存储在SQLite数据库中。我怎么能做到这一点?

var datetime = LocalDateTime.now()
var longdt: Long = getString(datetime).toLong()

共有1个答案

公良高刚
2023-03-14

可以使用ToEpochSecond()OfePochSecond()Long值精确到秒。

示例(Java)

LocalDateTime now = LocalDateTime.now();
long nowInSeconds = now.toEpochSecond(ZoneOffset.UTC);
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(nowInSeconds, 0, ZoneOffset.UTC);

System.out.println("now = " + now);
System.out.println("nowInSeconds = " + nowInSeconds);
System.out.println("dateTime = " + dateTime);

输出

now = 2020-05-12T12:12:36.984263200
nowInSeconds = 1589285556
dateTime = 2020-05-12T12:12:36
LocalDateTime now = LocalDateTime.now();
long nowInMillis = now.toEpochSecond(ZoneOffset.UTC) * 1000
                 + now.get(ChronoField.MILLI_OF_SECOND);
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(nowInMillis / 1000,
                  (int) (nowInMillis % 1000 * 1000000), ZoneOffset.UTC);

System.out.println("now = " + now);
System.out.println("nowInMillis = " + nowInMillis);
System.out.println("dateTime = " + dateTime);
now = 2020-05-12T12:16:38.881510700
nowInMillis = 1589285798881
dateTime = 2020-05-12T12:16:38.881

如果需要,请指定utc以外的区域偏移量,但在这种情况下,您实际上应该使用zoneddatetimeoffsetdatetime而不是localdatetime

 类似资料:
  • 我遇到的最后一个问题与这里的链接相同:flexbox项目的宽度被忽略 一切看起来都很好,但在最后一刻,我想更改flex容器的方向,所以我添加了

  • 一直让我抓狂的是发现一个简单的东西:Swift中的字符串长度。 否,不能使用 因为endIndex不是Int并且不能转换为in。这整件事快把我逼疯了,我不知道该怎么办。任何帮助都将不胜感激!

  • 这里对python非常陌生。如何将很长的字典值拆分为两行,同时在使用print()输出时仍显示为一行?请参见下面的代码。 我尝试过使用三重引号(即“”),但没有成功,因为我认为从技术上讲,值不是字符串。

  • 我必须制作一个Java程序,在给定的字符串中找到长度为n的所有重复子字符串。输入是字符串非常长,暴力方法需要花费太多时间。 我一直在尝试: 目前我正在分别查找每个子字符串,并使用KMP alogrithm检查该子字符串的重复。这也花了太多时间。 解决这个问题的更有效方法是什么?

  • 我做错了什么,怎么修复?

  • 我确信python有一种内置的方法来创建一个x大小的列表,其中的内容是0到x-1,但我不知道如何做到这一点。我在谷歌上搜索过,也在这里搜索过,我肯定我没有使用正确的措辞来找到我需要的东西。请帮忙。 <代码>len([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])=10