Created
August 18, 2016 14:31
-
-
Save amilos/1016084be3e7952f3e9353543dacd357 to your computer and use it in GitHub Desktop.
Using NodaTime Period class to serialize/deserialize ISO 8601 duration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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