mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-02-15 12:45:01 +00:00
Util methods for parsing a JSON datetime value
This commit is contained in:
@@ -1,8 +1,11 @@
|
|||||||
using System.Linq;
|
using System;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using ICD.Common.Properties;
|
using ICD.Common.Properties;
|
||||||
using ICD.Common.Utils.Extensions;
|
using ICD.Common.Utils.Extensions;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
namespace ICD.Common.Utils.Json
|
namespace ICD.Common.Utils.Json
|
||||||
{
|
{
|
||||||
@@ -12,6 +15,9 @@ namespace ICD.Common.Utils.Json
|
|||||||
[PublicAPI]
|
[PublicAPI]
|
||||||
public static class JsonUtils
|
public static class JsonUtils
|
||||||
{
|
{
|
||||||
|
// 2016-02-26T19:24:59
|
||||||
|
private const string DATE_FORMAT = @"yyyy-MM-dd\THH:mm:ss";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Forces Newtonsoft to cache the given type for faster subsequent usage.
|
/// Forces Newtonsoft to cache the given type for faster subsequent usage.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -23,6 +29,49 @@ namespace ICD.Common.Utils.Json
|
|||||||
JsonConvert.DeserializeObject<T>(serialized);
|
JsonConvert.DeserializeObject<T>(serialized);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the token as a DateTime value.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[PublicAPI]
|
||||||
|
public static DateTime ParseDateTime(JToken token)
|
||||||
|
{
|
||||||
|
if (token == null)
|
||||||
|
throw new ArgumentNullException("token");
|
||||||
|
|
||||||
|
#if SIMPLSHARP
|
||||||
|
return DateTime.ParseExact((string)token, DATE_FORMAT, CultureInfo.CurrentCulture);
|
||||||
|
#else
|
||||||
|
return (DateTime)token;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the token as a DateTime value.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <param name="output"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[PublicAPI]
|
||||||
|
public static bool TryParseDateTime(JToken token, out DateTime output)
|
||||||
|
{
|
||||||
|
if (token == null)
|
||||||
|
throw new ArgumentNullException("token");
|
||||||
|
|
||||||
|
output = default(DateTime);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
output = ParseDateTime(token);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (InvalidCastException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Pretty-prints the JSON document.
|
/// Pretty-prints the JSON document.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
Reference in New Issue
Block a user