Home > Software engineering >  Trying to get Server Timestamp before Document is added to cloud (Firestore)
Trying to get Server Timestamp before Document is added to cloud (Firestore)

Time:05-25

Trying to get the server timestamp at the CreatedAt document field before the document is added to the cloud. So it could be applied to the Time property and also saved locally, However this is what I get: Document Properties once saved on cloud.

My ChatTestMessageGroup Model

public class ChatTestMessageGroup : TimeTest
{
    public long MessageId { get; set; }
    public string Message { get; set; }
    public string Time { get; set; }
}

public class TimeTest
{
    [ServerTimestamp]
    public Timestamp CreatedAt { get; set; }
    public Timestamp StampAt { get; set; }
}

Send Message Execution code

private async Task SendTestMessageAsync()
{
    if (string.IsNullOrWhiteSpace(Message)) return;

    // under testing.
    var test = new ChatTestMessageGroup()
    {
        MessageId = new Timestamp().ToDateTime().Ticks,
        Message = Message.Trim(),
    };
    test.Time = $"{test.CreatedAt.ToDateTime():HH:mm}";
    await CloudService.CS.SendMessageAsync(test);
    Message = "";
}

Write To Cloud Code

public async Task SendMessageAsync(ChatTestMessageGroup testMessage)
{
    IDocumentReference doc = CrossCloudFirestore.Current.Instance.Collection("Testing").Document(DateTime.Now.Day.ToString());
        
    await doc.Collection("Tester").Document(${testMessage.CreatedAt.Seconds}").SetAsync(testMessage);
}

The plugin I'm using Plugin.CloudFirestore

CodePudding user response:

Trying to get the server timestamp at the CreatedAt document field before the document is added to the cloud.

This is not possible. The time is taken at the server the moment the document is created. The client app can't be certain what the time is on the server because its own clock could be wrong. You can only get the timestamp that was written by reading the document back.

CodePudding user response:

Documents don't have any sort of metadata like this in FireStore. After you create the document, if you didn't originally add a creation timestamp to it, you won't be able to find it after the fact. You'll want to get this metadata prior to uploading.

Are are some examples of how to do this already on stack overflow:

How to get File Created Date and Modified Date

Here's the MSDN way of getting that info:

https://docs.microsoft.com/en-us/dotnet/api/system.io.file.getcreationtime?view=net-6.0

  • Related