format date in linq query result

g.Key is nullable because that's the signature of EntityFunctions.TruncateTime. http://msdn.microsoft.com/en-us/library/dd395596.aspx.

To exit from Linq to Entities, you can leave the query as is, and project it after the fact:

return Json(query.AsEnumerable().Select(r => new 
    {
        date = r.date.GetValueOrDefault().ToString("dd.MM.yyyy"),
        users = r.users,
        visits = r.visits
    }), JsonRequestBehavior.AllowGet);

It's not pretty, but that's Linq to Entities for you.


Assuming you're using JSON.NET as the JSON serializer, you can apply the JsonConverterAttribute to the date property to specify a custom converter.

[JsonConverter(typeof(MyDateConverter))]
public DateTime? date { get; set; }

You can use the DateTimeConverterBase class as a base class for your converter.

Here's a possible implementation for MyDateConverter:

class CustomDateTimeConverter : DateTimeConverterBase
{
    private const string Format = "dd.MM.yyyy";

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        DateTime d = (DateTime)value;
        string s = d.ToString(Format);
        writer.WriteValue(s);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (s == null)
            return null;
        string s = (string)reader.Value;
        return DateTime.ParseExact(s, Format, null);
    }
}

Another option is to exclude the date property from the serialization (using the JsonIgnoreAttribute), and add another property of type String that converts to and from the desired format. Here's an implementation of this solution:

public class UserCountResult
{
    [JsonIgnore]
    public DateTime? date { get; set; }
    [JsonProperty("date")]
    public string DateAsString
    {
        get
        {
            return date != null ? date.Value.ToString("dd.MM.yyyy") : null;
        }
        set
        {
            date = string.IsNullOrEmpty(value) ? default(DateTime?) : DateTime.ParseExact(value, "dd.MM.yyyy", null);
        }
    }

    public int users { get; set; }
    public int visits { get; set; }
}

Something like this should work:

date = new Date(parseInt(g.Key.substr(6)));

The substr will pull off the "/Date(" string, parseInt will pull just the integer and Date will give you a new date object.

EDIT:

Just found this SO question that supports this answer.

How do I format a Microsoft JSON date?

Tags:

C#

Linq