PercivalMcGullicuddy
PercivalMcGullicuddy

Reputation: 5553

C# - How to format datetime to remove trailing zeros

I'm setting up an orchestration class that handles multiple actions as one big transaction. For each of these transactions I give them the same time-stamp instantiated at the beginning of the orchestration.

I user the following line:

 var transactionTimestamp =  DateTime.UtcNow.ToString("o");

I have a constraint in the system that dictates that the time stamp cannot have any trailing zeros.

For example:

2013-06-26T19:51:38.0083980Z //bad
2013-06-26T19:51:38.008398Z  //good
2013-06-26T19:51:38.0083988Z //good

Upvotes: 2

Views: 3372

Answers (3)

Egg
Egg

Reputation: 2066

The built-in DateTime format "o" is comparable to the custom format of: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK". If you just use that format, but replace the lower-case f's with upper case ones, there will be no trailing zeros.

ie

DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFFK");

Upvotes: 9

evanmcdonnal
evanmcdonnal

Reputation: 48114

I would write my own help method like;

public string GetDtString(DateTime dt)
{
    RegEx rgx = new RegEx("[1-9]0+Z\b");
    return rgx.Replace(dt.ToString("o"), System.String.Empty);
}

It basically just returns the dt string with all 0's which occur after a digit 1-9 and before Z\b (Z followed by a word boundary) with an empty string.

Upvotes: 1

recursive
recursive

Reputation: 86124

You can achieve this fairly easily using Regex. Here's one way.

string result = Regex.Replace("2013-06-26T19:51:38.0083980Z", "0+Z$", "Z");
// result == "2013-06-26T19:51:38.008398Z"

string result2 = Regex.Replace("2013-06-26T19:51:38.0083988Z", "0+Z$", "Z")
// result2 == "2013-06-26T19:51:38.0083988Z"

Upvotes: 3

Related Questions