Search code examples
c#nodatime

How can I parse "1:15 P.M." into a NodaTime LocalTime?


Parsing "1:15 pm" is easy:

var pattern = LocalTimePattern.CreateWithInvariantCulture("h:mm tt");
var time = pattern.Parse("1:15 pm").Value;

However, this doesn't work with the similar forms "1:15 P.M.", "1:15 PM", or "1:15 p.m."

Is there any built in support for those other forms of am/pm specifier, or does it need to be handled with string pre-processing?


Solution

  • Firstly, the "1:15 PM" version should work already - it does for me.

    If you want to allow "P.M" or "p.m". you'll need to create a culture with appropriate AM/PM signifiers. That's easy enough to do:

    using System;
    using System.Globalization;
    using NodaTime.Text;
    using NodaTime;
    
    class Program
    {
        static void Main()
        {
            var culture = (CultureInfo) CultureInfo.InvariantCulture.Clone();
            culture.DateTimeFormat.AMDesignator = "a.m.";
            culture.DateTimeFormat.PMDesignator = "p.m.";
            string text = "1:15 P.M.";
            var pattern = LocalTimePattern.Create("h:mm tt", culture);
            var value = pattern.Parse(text).Value;
            Console.WriteLine(value);
        }   
    }
    

    However, note that at this point, pm and am won't work - if you need to handle both formats, you'll need to create multiple patterns and see which one (if any) parses the text successfully.