Skip to content

Instantly share code, notes, and snippets.

@amilos
Created August 18, 2016 14:31
Show Gist options
  • Save amilos/1016084be3e7952f3e9353543dacd357 to your computer and use it in GitHub Desktop.
Save amilos/1016084be3e7952f3e9353543dacd357 to your computer and use it in GitHub Desktop.
Using NodaTime Period class to serialize/deserialize ISO 8601 duration
using System;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using NodaTime;
using NodaTime.Serialization.JsonNet;
namespace FormattingUtils
{
public static class Extensions
{
public static Period ToPeriod(this string input)
{
var js = JsonSerializer.Create(new JsonSerializerSettings());
js.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
var quoted = String.Concat(@"""", input, @"""");
return js.Deserialize<Period>(new JsonTextReader(new StringReader(quoted)));
}
}
class Program
{
static void Main(string[] args)
{
// 15 years
var p = "P15Y".ToPeriod();
Console.WriteLine(String.Format("{0} years is represented as P15Y", p.Years));
// 6 months
Console.WriteLine("6 months is represented as " + Period.FromMonths(6).ToString());
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment