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**
CodePudding user response:
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
CodePudding user response:
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);