Skip to content

Instantly share code, notes, and snippets.

@ThomasPe
Created April 5, 2022 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasPe/cf5bf8b062c85d897ebd7dd35aa42609 to your computer and use it in GitHub Desktop.
Save ThomasPe/cf5bf8b062c85d897ebd7dd35aa42609 to your computer and use it in GitHub Desktop.
Convert DateTime.Now to an ever-decreasing Ticks String to be used as Keys in Azure Table Storage
/// <summary>
/// Returns an ever-decreasing number as string to be used as PartitionKey or RowKey.
/// Ensures that newly created entities are always "on top" and returned first in queries
/// </summary>
/// <returns></returns>
public static string TicksKey()
{
return (DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks).ToString("d19");
}
/// <summary>
/// Converts TicksKey back to DateTimeOffset
/// </summary>
/// <param name="ticksKey"></param>
/// <returns></returns>
public static DateTimeOffset TicksKeyToDateTimeOffset(string ticksKey)
{
return new DateTimeOffset(DateTime.MaxValue.Ticks - long.Parse(ticksKey), TimeSpan.Zero);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment