Created
June 29, 2011 03:08
-
-
Save dkarzon/1052894 to your computer and use it in GitHub Desktop.
Better handling of JSON formated DateTime in WCF
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.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Globalization; | |
/// <summary> | |
/// Class to help get around the craziness of WCF DateTime formats (Use this class instead of DateTime for WebService Models) | |
/// </summary> | |
public class WCFDate | |
{ | |
public static string DateTimeFormat = "yyyy-MM-dd hh:mm:ss zz"; | |
/// <summary> | |
/// The Date as a formatted string (Format set by the Format helper class) | |
/// </summary> | |
public string Data { get; set; } | |
/// <summary> | |
/// Basic constructor (with no value) | |
/// </summary> | |
public WCFDate() { } | |
/// <summary> | |
/// String constructor setting a Formatted string for the DateTime | |
/// </summary> | |
/// <param name="data"></param> | |
public WCFDate(string data) | |
{ | |
Data = data; | |
} | |
/// <summary> | |
/// DateTime constructor, sets the Data to the formatted String from the DateTime | |
/// </summary> | |
/// <param name="date"></param> | |
public WCFDate(DateTime date) | |
{ | |
Data = date.ToString(DateTimeFormat); | |
} | |
/// <summary> | |
/// DateTime constructor, sets the Data to the formatted String from the DateTime | |
/// </summary> | |
/// <param name="date"></param> | |
public WCFDate(DateTime? date) | |
{ | |
if (date.HasValue) | |
{ | |
Data = date.Value.ToString(DateTimeFormat); | |
} | |
} | |
/// <summary> | |
/// Check if the class is holding a Date or not | |
/// </summary> | |
public bool HasDate | |
{ | |
get | |
{ | |
return !string.IsNullOrWhiteSpace(Data); | |
} | |
} | |
/// <summary> | |
/// Gets the DateTime the class represents | |
/// </summary> | |
/// <returns></returns> | |
public DateTime GetDate() | |
{ | |
try | |
{ | |
return DateTime.ParseExact(Data, DateTimeFormat, CultureInfo.CurrentCulture); | |
} | |
catch | |
{ | |
return new DateTime(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why does this solve the problem?