How to Store Dates and Times That Sort Correctly in Azure Cosmos DB with C#
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
string <text> = <time>.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ", CultureInfo.InvariantCulture);
| Part | What 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, dd | The year as four digits, the month from 01 to 12, and the day from 01 to 31 |
HH, mm, ss | The hour on a 24-hour clock from 00 to 23, then the minute and the second, each from 00 to 59 |
fffffff | The ten millionths of a second in a date and time value. Always seven digits, zeros included |
-, T, . and Z | Not 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.InvariantCulture | The 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 --versionprints a version that starts with10.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
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:
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:
<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:
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");
AccountEndpointis your account's URI, from its Overview page in the Azure portal.UseSystemTextJsonSerializerWithOptionsmakes the SDK write and read items with System.Text.Json.JsonSerializerOptions.Webwrites property names in camelCase, soDeviceIdis stored asdeviceId, the property the partition key path names, andAtasat.keyis 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
// 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:
record DoorEvent(string Id, string DeviceId, string Name, DateTime At);
record StoredEvent(string Name, string At);
tenis 10:00 on 3 December 2026, andDateTimeKind.Utcmarks it as UTC.AddMilliseconds(500)andAddSeconds(1)give the other two times: half a second and one second later.DoorEventis the item. ItsAtis aDateTime, so the serializer decides how the time is written into the JSON.UpsertItemAsyncstores each event, or replaces it if an earlier run left it behind.
Step 4: List Them Sorted by Time
// 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.atsorts the events by their storedatproperty.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.StoredEventreadsatas a plainstring, 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
dotnet run
2026-12-03T10:00:00.5Z Light on
2026-12-03T10:00:00Z Door opened
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:
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:
using System.Globalization;
Pass each time through a new method, SortableUtc:
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:
// 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 literalZsays so.fffffffwrites all seven digits of the fraction, zeros included, so every time has the same length and the same layout.CultureInfo.InvariantCulturesupplies the time separator, so the machine's own culture doesn't change the string.string Atstores 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
dotnet run
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
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);

Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Storing a DateTime and sorting on it with ORDER BY | Times with fewer fraction digits sort before the whole second, as in Step 5 | Store the recommended string |
Formatting with capital FFFFFFF | The reference: Trailing zeros aren't displayed, which is the same problem again | Use lowercase fffffff |
Writing a literal Z after a local time | The string claims UTC, but the time is off by the machine's offset from UTC | Call ToUniversalTime() first |
Creating a time with DateTimeKind.Unspecified that is really UTC | ToUniversalTime() treats it as local time and converts it | Create UTC times with DateTimeKind.Utc |
Leaving out CultureInfo.InvariantCulture | : is the current culture's time separator, which isn't a colon in every culture | Pass 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
- Store and query dates in Cosmos DB — the recommended format, and storing every date as UTC.
- DateTime and DateTimeOffset support in System.Text.Json — the format the serializer writes, and why it drops trailing zeros.
- Custom date and time format strings — every specifier in the format string.
- DateTime.ToUniversalTime — what it does with each
Kind.
