Including trailing zeroes when formatting NodaTime instant?

Viewed 138

Using NodaTime 2.4.x

If I create an Instant that starts bang on a second, and then try and format it with a Pattern that includes milliseconds / nanoseconds, the trailing zeroes are cut off.

e.g.

using System;
using NodaTime;
using NodaTime.Text;

public class Program
{
    private static readonly InstantPattern _instantPattern 
            = InstantPattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFF'Z'");

    public static void Main()
    {
        var instantRound = Instant.FromUnixTimeMilliseconds(158507100000);
        var instantNotRound = Instant.FromUnixTimeMilliseconds(158507100001);
        Console.WriteLine(_instantPattern.Format(instantRound));
        Console.WriteLine(_instantPattern.Format(instantNotRound));
    }
}

Outputs

1975-01-09T13:45:00Z
1975-01-09T13:45:00.001Z

You can see this here

Is there anyway I could get the output to be the following, preferably using an inbuilt method:

1975-01-09T13:45:00.000000Z
1975-01-09T13:45:00.001000Z

Basically, keep the trailing zeroes.

1 Answers

You can refer to this page for the pattern specifiers. F will cause the insignificant trailing digits to be stripped. f will not.

You also used the wrong method names. It should be FromMillisecondsSinceUnixEpoch, not FromUnixTimeMilliseconds.

private static readonly InstantPattern _instantPattern 
        = InstantPattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;ffff'Z'");

public static void Main()
{
    var instantRound = Instant.FromMillisecondsSinceUnixEpoch(158507100000);
    var instantNotRound = Instant. FromMillisecondsSinceUnixEpoch(158507100001);
    Console.WriteLine(_instantPattern.Format(instantRound));
    Console.WriteLine(_instantPattern.Format(instantNotRound));
}
Related