【问题标题】:How do i convert firestore timestamp to date into different format en c#如何将firestore时间戳转换为不同的格式en c#
【发布时间】:2021-06-01 13:29:25
【问题描述】:

我正在尝试在 c# 中的 dateTimePicker 值中添加时间戳,我不知道这是否可能,但我遇到了错误。如果可能的话,我想把它放在格式(“dd/MM/yyyy”)。

dateTimeDate.Value = student.date;

但我收到此错误,

Cannot implicitly pass the type "Google.Cloud.firestore.Timestamp" in "System.DateTime". 

所以我试试这个,但还是不行。

dateTimeDate.Value = student.date.ToDateTime();

我该如何解决这个问题,我也想知道如何将其转换为字符串以放入文本框。

【问题讨论】:

  • 好像dateTimeDate和student.date的类型不一样,可以去定义看看
  • 你在使用student.date.ToDateTime();时有没有报错?
  • 不,但我没有得到 Firestore 中的日期。出于某种原因,当我使用 student.date.ToDateTime () 时,我总是得到 01/01/1970。
  • 不太清楚为什么您使用的数据类型未列为 firestore cloud.google.com/firestore/docs/concepts/data-types 支持的数据类型。您可能想改用日期和时间。您必须进行大量转换工作才能将 google.cloud.firestore.Timestamp 转换为 .net DateTime,因为它们使用完全不同的 epoch 值。
  • @sebas9981 欢迎来到 StackOverflow,您能否提供您想出的解决方案作为您问题的答案并接受它?这将使社区的其他成员更容易参考它,以防他们遇到相同的问题,这也将有助于提高您在 StackOverflow 上的声誉,如果您对如何做到这一点有任何疑问,您可以关注 thesethese 说明。

标签: c# firebase datetime google-cloud-firestore timestamp


【解决方案1】:

Firestore 返回 Google.Cloud.Firestore.Timestamp 对象 如果我们将它转​​换为字符串看起来像:

时间戳:2021-04-03T10:34:48.865466Z

我们可以将其转换为DateTime对象:

DateTime result = DateTime.ParseExact(TIMESTAMP.ToString().Replace("Timestamp:", "").Trim(), 
    "yyyy-MM-ddTHH:mm:ss.ffffffK", null);

【讨论】:

  • 已经有一些方法可以让你转换为.a DateTime。 Google.Cloud.Firestore.Timestamp 类型带有一个预制方法 .ToDateTime() ,当在 Timestamp 对象上运行时,将返回一个 DateTime 对象
【解决方案2】:

在 C# 中,您可以将从 Firestore 返回的对象转换为 Firebase.Firestore.Timestamp。然后您将可以访问<Timestamp>.ToDateTime() 方法。

using Firebase.Firestore;

// code to load data from Firestore
// snapshot is the result of docReference.GetSnapshotAsync()

var dict = snapshot.ToDictionary();
var timestamp = (Timestamp)dict["myTimestampFieldName"];
var myDateTime = timestamp.ToDateTime();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 2021-12-10
    • 2021-09-17
    • 1970-01-01
    • 2019-11-30
    • 2017-05-20
    • 1970-01-01
    相关资源
    最近更新 更多