2

I am using a mono self hosted servicestack application with the ServiceStack.Razor rendering. In the application the user enters into a form a UK date (dd/mm/yyyy) but this is converted to a US date (mm/dd/yyyy) on a HTTP POST.

In a normal MVC application I would do this using model binding as shown here ASP.NET MVC3: Force controller to use date format dd/mm/yyyy

How do you do this in ServiceStack as I could not find anything about it.

Community
  • 1
  • 1
Ollie
  • 1,140
  • 8
  • 26
  • 1
    If you know how it is going to be delivered, can't you just convert it back to your desired format in your service? Also, check this out https://github.com/ServiceStack/ServiceStack.Text/blob/master/tests/ServiceStack.Text.Tests/JsonTests/JsonDateTimeTests.cs – user1477388 Mar 05 '14 at 14:31
  • It would not work as I would get invalid dates when the day goes over 12 as it would think the month in US dates was not valid. I could use a string but that would defeat the point of using binding. – Ollie Mar 05 '14 at 15:25

1 Answers1

3

You can use custom serializers/deserializers to globally control the serialization and deserialization of DateTime values:

In your AppHost:

using ServiceStack.Text;

JsConfig<DateTime>.SerializeFn = SerializeAsUKDate;
// Also, if you need to support nullable DateTimes:
JsConfig<DateTime?>.SerializeFn = SerializeAsNullableUKDate;

public static string SerializeAsUKDate(DateTime value)
{
    // or whatever you prefer to specify the format/culture
    return value.ToString("dd/MM/yyyy");
}

public static string SerializeAsNullableUKDate(DateTime? value)
{
    return value.HasValue ? SerializeAsUKDate(value.Value) : null;
}

You may or may not need to specify DeSerializeFn to ensure that dates are parsed correctly. The ServiceStack.Text date deserializer is pretty robust.

JsConfig<DateTime>.DeSerializeFn = DeSerializeAsUKDate;

public static DateTime DeSerializeAsUKDate(string value)
{
    // date parsing logic here
    // ServiceStack.Text.Common.DateTimeSerializer has some helper methods you may want to leverage
}
Mike Mertsock
  • 11,825
  • 7
  • 42
  • 75