'Trailing Zeros are getting trimmed when using FFFFFF C#
When I am executing the below code, Zeros got trimmed off.
But I need the output along with Zeros. If the milliseconds is zero I should not display that as well.
string date = dateTime.ToString("yyyy-MM-dd HH:mm:ss.FFFFFFFZ", CultureInfo.InvariantCulture);```
**Output: 2021-08-08 08:08:34.196Z
Expected: 2021-08-08 08:08:34.196000Z**
Case 2:
```DateTime dateTime = DateTime.Parse("2021-08-08T08:08:34");
string date = dateTime.ToString("yyyy-MM-dd HH:mm:ss.fffffffZ", CultureInfo.InvariantCulture);```
**Output :2021-08-08 08:08:34.0000000Z
Expected: 2021-08-08 08:08:34Z**
Solution 1:[1]
My interpretation of your rule is: "If the milliseconds component is exactly 0, don't render it at all. Otherwise, render any milliseconds component to six (or seven?) places".
There's no built-in format specifier for this, so you'll have to write a bit of your own code.
Look at dateTime.Millisecond. If it's zero, then you don't want any milliseconds compoment. If it's non-zero, then you want ffffff. Something like:
string millisecondsFormat = dateTime.Millisecond == 0 ? "" : ".fffffff";
string date = dateTime.ToString($"yyyy-MM-dd HH:mm:ss{millisecondsFormat}Z", CultureInfo.InvariantCulture)
This gives the following input/output:
- new DateTime(2020, 1, 1, 5, 6, 7): 2020-01-01 05:06:07Z
- new DateTime(2020, 1, 1, 5, 6, 7, 800): 2020-01-01 05:06:07.800000Z
Solution 2:[2]
you can do a trick like:
string date = datetime.ToString(datetime.Millisecond == 0 ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd HH:mm:ss.fffffffZ", CultureInfo.InvariantCulture);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Aria |
