How can I get the value of a date into a string in the format YYYY-MM-DDThh:mm:ss.sssZ for CosmosDB?

Viewed 765

The CosmosDB database I am using suggests I store DateTime in a string.

Working with Dates in Azure Cosmos DB

So I am trying to do this:

string DateAndTime = DateTime.Now.ToString()

but it's not giving me the correct format. Is there a method to do this and to convert it to this exact format: YYYY-MM-DDThh:mm:ss.sssZ ?

2 Answers

If you're not already using the DocumentClient, you could use this to interface with your collection.

Using the DocumentClient means that you can define your document types as you wish, without having to manually convert fields to string. For example, you could use the following type to create/query documents out of the collection:

public class CosmosDocument
{
    [JsonProperty("id")]
    public string Id { get; set; }

    public DateTime TimeStamp { get; set; }

}

The DocumentClient will then serialize/deserialize/model-bind the data, including DateTime values for you.

The serialization is configurable if you need to make any changes to the default settings.

EDIT

As noted in the comments, CosmosClient is the newer version that provides the same functionality described above.

According to Custom date and time format strings, you should use something like that

string DateAndTime = DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss.sssz");

It will give you the following string 2020-04-04T11:19:06.06+3

yyyy means four-digit year (YYYY format doesn't exist), dd represents the day of the month (from 01 to 31). z is used for offset between your local time zone and UTC

The capital Z literal in string indicates that datetime is in UTC format (according to ISO 8601 standard). To get it literally in a result string you may use DateTime.UtcNow instead of DateTime.Now with Z literal or K specifier at the end

string DateAndTime = DateTime.UtcNow.ToString("yyyy-MM-ddThh:mm:ss.sssK");

It gives you 2020-04-04T08:49:22.22Z (current datetime in UTC format). K specifier will add Z literal for UTC dates and offset (in zzz format) for local dates

Related