DK Development

The random output of a Windows developer.

DK Development

The random output of a Windows developer.




DateTime + WCF: How I tamed the beast

I have been working a bit with WCF lately and like everyone else use Json with WCF I ran into some issues with DateTime formats. I kept trying to find a valid solution to this where it outputted a readable value.

Eventually I started outputting the DateTime as a formatted string and this worked, but it meant I have to create new string variables in all of my classes instead of the DateTimes that I already had and was using, but then I still needed the variable in its DateTime form.

So I came up with the WCFDate class, at its heart this class outputs a string in a set format, this allows it to be easily read by what ever needs to. I could then replace all of my DateTimes with WCFDate and all was good in the world.

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 
    /// </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();
        }
    }
}

Follow the Gist of this class or feel free to add to it.

blog comments powered by Disqus