简体   繁体   中英

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

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");

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM