Create a custom type converter as follows:
public class DateTimeOffsetConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(DateTimeOffset)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var s = value as string; if (s != null) { if (s.EndsWith("Z", StringComparison.OrdinalIgnoreCase)) { s = s.Substring(0, s.Length - 1) + "+0000"; } DateTimeOffset result; if (DateTimeOffset.TryParseExact(s, "yyyyMMdd'T'HHmmss.FFFFFFFzzz", CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) { return result; } } return base.ConvertFrom(context, culture, value); }
In your startup sequence, for example WebApiConfig.Register , dynamically add this type of converter to the DateTimeOffset structure:
TypeDescriptor.AddAttributes(typeof(DateTimeOffset), new TypeConverterAttribute(typeof(DateTimeOffsetConverter)));
Now you can simply pass the DateTimeOffset values ββin a compact form of ISO8601, which does not allow hyphens or colons that interfere with the URL:
api/values/20171231T012345-0530 api/values/20171231T012345+0000 api/values/20171231T012345Z
Note that if you have fractional seconds, you may need to include a trailing braid in the URL .
api/values/20171231T012345.1234567-0530/
You can also queue it if you want:
api/values?foo=20171231T012345-0530
Matt Johnson-Pint
source share