Skip to main content

How to Store Dates and Times That Sort Correctly in Azure Cosmos DB with C#

· 15 min read
Jagdish Kumawat
Founder @ Dewiride

A C# DateTime that the Azure Cosmos DB SDK stores for you can sort in the wrong order: in this run, ORDER BY c.at listed an event at 10:00:00.5 before one at 10:00:00. Storing each time as a UTC string with seven digits after the seconds, the format Microsoft recommends, puts them back in the order they happened.

Cosmos DB stores JSON, and JSON has no date type. Microsoft's page on dates says it plainly: It doesn't directly support a DateTime type. and So, you must store date and time information as strings. How those strings are written decides how they sort, and the format the SDK's serializers pick for a DateTime isn't the one that sorts.

Syntax​

Syntax
string <text> = <time>.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ", CultureInfo.InvariantCulture);
PartWhat it is
<time>The DateTime to store
<text>The string to put in the item, such as 2026-12-03T10:00:00.5000000Z
ToUniversalTime()Converts <time> to UTC. A time whose Kind is Utc stays as it is, a Local time is converted, and an Unspecified one is assumed to be a local time, and the conversion is performed as if Kind were Local
yyyy, MM, ddThe year as four digits, the month from 01 to 12, and the day from 01 to 31
HH, mm, ssThe hour on a 24-hour clock from 00 to 23, then the minute and the second, each from 00 to 59
fffffffThe ten millionths of a second in a date and time value. Always seven digits, zeros included
-, T, . and ZNot format specifiers, so they're copied as they are: All other characters are always interpreted as character literals and, in a formatting operation, are included in the result string unchanged. The Z says the time is UTC, which ToUniversalTime() makes true
:The time separator, which comes from a culture: The appropriate localized time separator is retrieved from the DateTimeFormatInfo.TimeSeparator property of the current or specified culture.
CultureInfo.InvariantCultureThe culture to take the time separator from, instead of the machine's current culture. In this run it wrote :

This is the format of Microsoft's recommendation: The recommended format for date and time strings is yyyy-MM-ddTHH:mm:ss.fffffffZ, which follows the ISO 8601 UTC standard. Along with it: Store all dates in Cosmos DB as UTC.

The Example​

A door sensor at a front door sends events. The console app DoorEvents stores three of them, half a second apart: Door opened at 10:00:00 UTC on 3 December 2026, Light on at 10:00:00.5 and Alarm off at 10:00:01. They go into a container events in the database howto, with the partition key path /deviceId, and the app lists them with ORDER BY c.at. The first version stores each time as a DateTime, the second as a string in the recommended format. The app signs in with my Azure CLI account, and deletes the events at the end, so it can run again.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.
  • The Azure CLI, signed in with az login. The app uses that sign-in.
  • A Cosmos DB for NoSQL container whose partition key path is /deviceId, and a Cosmos DB data role for your account on it, such as Cosmos DB Built-in Data Contributor: Connect using role-based access control and Microsoft Entra ID.

Step 1: Create a Console App and Add the Packages​

Terminal
dotnet new console -n DoorEvents
cd DoorEvents
dotnet add package Microsoft.Azure.Cosmos --version 3.64.0
dotnet add package Newtonsoft.Json --version 13.0.4
dotnet add package Azure.Identity --version 1.21.0

dotnet new console creates the project in a new folder DoorEvents, cd moves into it, and each dotnet add package adds one package at the version given. The last command ends with these lines:

Output (the last lines of the last command)
info : PackageReference for package 'Azure.Identity' version '1.21.0' added to file '/Users/you/source/DoorEvents/DoorEvents.csproj'.
info : Generating MSBuild file /Users/you/source/DoorEvents/obj/DoorEvents.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/DoorEvents/obj/project.assets.json
log : Restored /Users/you/source/DoorEvents/DoorEvents.csproj (in 722 ms).

The project file now references the three packages:

DoorEvents.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.21.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.64.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>

</Project>

Microsoft.Azure.Cosmos is the Cosmos DB SDK, Newtonsoft.Json is a package the SDK requires you to reference yourself, and Azure.Identity has the Microsoft Entra ID credentials. How to Connect to Azure Cosmos DB with Microsoft Entra ID in C# explains each one and the client in detail.

Step 2: Connect​

Replace Program.cs, starting with the client:

Program.cs (the client)
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

// The account's URI, from its Overview page in the Azure portal.
const string AccountEndpoint = "https://cosmos-maf-servicedesk-4224.documents.azure.com:443/";

using CosmosClient client = new(AccountEndpoint, new AzureCliCredential(), new CosmosClientOptions
{
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});
Container events = client.GetContainer("howto", "events");
PartitionKey key = new("front-door");
  • AccountEndpoint is your account's URI, from its Overview page in the Azure portal.
  • UseSystemTextJsonSerializerWithOptions makes the SDK write and read items with System.Text.Json. JsonSerializerOptions.Web writes property names in camelCase, so DeviceId is stored as deviceId, the property the partition key path names, and At as at.
  • key is the partition key value of the front door's sensor, front-door. All three events go into that partition.

Step 3: Store Three Events with a DateTime​

Program.cs (the events, first version)
// Three things that happened at the front door, half a second apart.
DateTime ten = new(2026, 12, 3, 10, 0, 0, DateTimeKind.Utc);
DoorEvent[] happened =
[
new("1", "front-door", "Door opened", ten),
new("2", "front-door", "Light on", ten.AddMilliseconds(500)),
new("3", "front-door", "Alarm off", ten.AddSeconds(1)),
];
foreach (DoorEvent doorEvent in happened)
{
await events.UpsertItemAsync(doorEvent, key);
}

At the end of the file go the two types:

Program.cs (the end of the file, first version)
record DoorEvent(string Id, string DeviceId, string Name, DateTime At);

record StoredEvent(string Name, string At);
  • ten is 10:00 on 3 December 2026, and DateTimeKind.Utc marks it as UTC.
  • AddMilliseconds(500) and AddSeconds(1) give the other two times: half a second and one second later.
  • DoorEvent is the item. Its At is a DateTime, so the serializer decides how the time is written into the JSON.
  • UpsertItemAsync stores each event, or replaces it if an earlier run left it behind.

Step 4: List Them Sorted by Time​

Program.cs (the query and the clean up)
// Read them back sorted by time, with each time as Cosmos DB stores it.
FeedIterator<StoredEvent> query = events.GetItemQueryIterator<StoredEvent>(
"SELECT c.name, c.at FROM c ORDER BY c.at",
requestOptions: new QueryRequestOptions { PartitionKey = key });
while (query.HasMoreResults)
{
foreach (StoredEvent stored in await query.ReadNextAsync())
{
Console.WriteLine($"{stored.At,-30} {stored.Name}");
}
}

// Remove the events, so the app can run again.
foreach (DoorEvent doorEvent in happened)
{
await events.DeleteItemAsync<DoorEvent>(doorEvent.Id, key);
}
  • ORDER BY c.at sorts the events by their stored at property.
  • QueryRequestOptions { PartitionKey = key } keeps the query in the front door's partition. How to Query the Items of One Partition in Azure Cosmos DB with C# explains this option.
  • StoredEvent reads at as a plain string, so the app prints each time exactly as Cosmos DB stores it.
  • {stored.At,-30} pads the time to 30 characters, so the names line up in a column.

Step 5: Run It​

Terminal
dotnet run
Output
2026-12-03T10:00:00.5Z Light on
2026-12-03T10:00:00Z Door opened
2026-12-03T10:00:01Z Alarm off

macOS-style terminal window titled Terminal — DoorEvents showing dotnet run with the events in the wrong order: 2026-12-03T10:00:00.5Z Light on first, then 2026-12-03T10:00:00Z Door opened, then 2026-12-03T10:00:01Z Alarm off

Light on came first, although the door opened half a second before it. Only Alarm off, a whole second later, is where it belongs.

Why the Order Is Wrong​

The three times aren't written the same way. 10:00:00Z has no fraction of a second at all, and 10:00:00.5Z has one digit. That's System.Text.Json's format by design. Microsoft's page on its date support: If the round-trip format representation of a DateTime or DateTimeOffset instance has trailing zeros in its fractional seconds, then JsonSerializer and Utf8JsonWriter will format a representation of the instance without trailing zeros. And when the fraction has all zeros in its fractional seconds, then JsonSerializer and Utf8JsonWriter will format a representation of the instance without fractional seconds. So half a second becomes .5, and a whole second has no fraction.

Cosmos DB sorts strings character by character. Microsoft's word for it is lexicographic: the first character that differs decides. Here are the first two times, one above the other:

The two times, one above the other
2026-12-03T10:00:00Z
2026-12-03T10:00:00.5Z

The first 19 characters, 2026-12-03T10:00:00, are the same. Next comes Z in one and . in the other, and in character order the period comes before the digits 0 to 9, which come before the letter Z. So every time with a fraction sorts before the same second written without one.

It isn't only System.Text.Json. In a separate run, I stored the same three events through the SDK's default serializer, Newtonsoft.Json, with only camelCase names set, and read the raw JSON of the same query. The times came back as 2026-12-03T10:00:00.5Z, 2026-12-03T10:00:00Z and 2026-12-03T10:00:01Z, in that order: the same short strings, and the same wrong order.

Microsoft's page on dates in Cosmos DB says that most applications can use the default string representation for DateTime, giving as the first reason: Strings can be compared, and the relative ordering of the DateTime values is preserved when they're transformed to strings. Both runs here show otherwise for the strings the SDK's serializers write. The time in that page's own example, 2014-09-15T23:14:25.7251173Z, ends in a digit other than zero, so no zeros were dropped from it.

Step 6: Store the Time as a Sortable String​

Make the format your code's decision instead of the serializer's. Add a using at the top of Program.cs:

Program.cs (the first line)
using System.Globalization;

Pass each time through a new method, SortableUtc:

Program.cs (the events)
DoorEvent[] happened =
[
new("1", "front-door", "Door opened", SortableUtc(ten)),
new("2", "front-door", "Light on", SortableUtc(ten.AddMilliseconds(500))),
new("3", "front-door", "Alarm off", SortableUtc(ten.AddSeconds(1))),
];

And replace the end of the file with the method and a DoorEvent whose At is a string:

Program.cs (the end of the file)
// The format Microsoft recommends for Cosmos DB: UTC, and always seven digits after the seconds.
static string SortableUtc(DateTime time) =>
time.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ", CultureInfo.InvariantCulture);

record DoorEvent(string Id, string DeviceId, string Name, string At);

record StoredEvent(string Name, string At);
  • ToUniversalTime() makes sure the time is UTC before the literal Z says so.
  • fffffff writes all seven digits of the fraction, zeros included, so every time has the same length and the same layout.
  • CultureInfo.InvariantCulture supplies the time separator, so the machine's own culture doesn't change the string.
  • string At stores the formatted text as it is: the serializer has nothing left to decide.

The query and the clean up stay as they were.

Step 7: Run It Again​

Terminal
dotnet run
Output
2026-12-03T10:00:00.0000000Z Door opened
2026-12-03T10:00:00.5000000Z Light on
2026-12-03T10:00:01.0000000Z Alarm off

macOS-style terminal window titled Terminal — DoorEvents showing dotnet run with the events in time order: 2026-12-03T10:00:00.0000000Z Door opened, 2026-12-03T10:00:00.5000000Z Light on, 2026-12-03T10:00:01.0000000Z Alarm off

Door opened, Light on, Alarm off: the order they happened in. Every time has seven digits after the seconds, so the strings line up character for character, and the first digit that differs is also the one that tells the times apart. That's what Microsoft means by Converting the date strings to this format allow for sorting of dates lexicographically.

The Complete File​

Program.cs
using System.Globalization;
using System.Text.Json;
using Azure.Identity;
using Microsoft.Azure.Cosmos;

// The account's URI, from its Overview page in the Azure portal.
const string AccountEndpoint = "https://cosmos-maf-servicedesk-4224.documents.azure.com:443/";

using CosmosClient client = new(AccountEndpoint, new AzureCliCredential(), new CosmosClientOptions
{
UseSystemTextJsonSerializerWithOptions = JsonSerializerOptions.Web,
});
Container events = client.GetContainer("howto", "events");
PartitionKey key = new("front-door");

// Three things that happened at the front door, half a second apart.
DateTime ten = new(2026, 12, 3, 10, 0, 0, DateTimeKind.Utc);
DoorEvent[] happened =
[
new("1", "front-door", "Door opened", SortableUtc(ten)),
new("2", "front-door", "Light on", SortableUtc(ten.AddMilliseconds(500))),
new("3", "front-door", "Alarm off", SortableUtc(ten.AddSeconds(1))),
];
foreach (DoorEvent doorEvent in happened)
{
await events.UpsertItemAsync(doorEvent, key);
}

// Read them back sorted by time, with each time as Cosmos DB stores it.
FeedIterator<StoredEvent> query = events.GetItemQueryIterator<StoredEvent>(
"SELECT c.name, c.at FROM c ORDER BY c.at",
requestOptions: new QueryRequestOptions { PartitionKey = key });
while (query.HasMoreResults)
{
foreach (StoredEvent stored in await query.ReadNextAsync())
{
Console.WriteLine($"{stored.At,-30} {stored.Name}");
}
}

// Remove the events, so the app can run again.
foreach (DoorEvent doorEvent in happened)
{
await events.DeleteItemAsync<DoorEvent>(doorEvent.Id, key);
}

// The format Microsoft recommends for Cosmos DB: UTC, and always seven digits after the seconds.
static string SortableUtc(DateTime time) =>
time.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ", CultureInfo.InvariantCulture);

record DoorEvent(string Id, string DeviceId, string Name, string At);

record StoredEvent(string Name, string At);

macOS-style code window titled Program.cs — DoorEvents showing three door events stored with SortableUtc, a query SELECT c.name, c.at FROM c ORDER BY c.at in the front-door partition that prints each stored time and name, the clean up, and SortableUtc, which calls ToUniversalTime and formats the time with yyyy-MM-ddTHH:mm.fffffffZ and CultureInfo.InvariantCulture

Common Mistakes​

MistakeWhat happensDo this instead
Storing a DateTime and sorting on it with ORDER BYTimes with fewer fraction digits sort before the whole second, as in Step 5Store the recommended string
Formatting with capital FFFFFFFThe reference: Trailing zeros aren't displayed, which is the same problem againUse lowercase fffffff
Writing a literal Z after a local timeThe string claims UTC, but the time is off by the machine's offset from UTCCall ToUniversalTime() first
Creating a time with DateTimeKind.Unspecified that is really UTCToUniversalTime() treats it as local time and converts itCreate UTC times with DateTimeKind.Utc
Leaving out CultureInfo.InvariantCulture: is the current culture's time separator, which isn't a colon in every culturePass the invariant culture

FAQ​

Can I store the time as a number instead?​

Yes. Microsoft's page: Alternatively, you can store DateTimes as Unix timestamps, that is, as a number representing the number of elapsed seconds since January 1, 1970. Cosmos DB's own _ts property works that way. The string format has one advantage Microsoft lists among its reasons: The dates as stored in JSON are human readable.

Do range filters work on these strings?​

Yes, if every time is UTC. Microsoft: Range queries with date and time strings as filters are only supported if the date and time strings are all in UTC. SortableUtc always writes UTC.

Why did only one pair of events swap?​

Because the order goes wrong only where a fraction meets a whole second. Alarm off, at 10:00:01Z, already differs from the other two in the last digit of the seconds, and that digit decides before any fraction is reached. Door opened and Light on share every character up to the seconds, so the Z of one and the . of the other decided between them.

Conclusion​

A DateTime in a C# item becomes a string in Cosmos DB, and the SDK's serializers write it as short as they can: no fraction for a whole second, and no trailing zeros. Strings sort character by character, so in this run ORDER BY c.at put 10:00:00.5 before 10:00:00. Store times as UTC strings with seven fraction digits, yyyy-MM-ddTHH:mm:ss.fffffffZ, formatted with ToUniversalTime() and CultureInfo.InvariantCulture, and character order is time order.

Additional Resources​