0

i have a class say something like this :

public class Product {
    public int Id { get; set; }
    public string Name{ get; set; }
    public DateTime CreatedDate{ get; set; }
    public DateTime UpdatedDate{ get; set }
}  

and want to convert all DateTime types to long when serializing to json , with this method :

private long convertDateToLong(DateTime datetime)
{
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    long ms = (long)(datetime - epoch).TotalMilliseconds;
    return ms;
}  

how can i do this in asp.net web api 2 ?

edit :
i have written this code but it doesn't affect the output :

class DateTimeSerializer : BufferedMediaTypeFormatter
{

    public DateTimeSerializer()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
    }

    public override bool CanReadType(Type type)
    {
        return false;
    }

    public override bool CanWriteType(Type type)
    {
        if (type == typeof (DateTime))
            return true;
        else
            return false;
    }

    public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
    {
        using (var writer = new StreamWriter(writeStream))
        {
            var datetime = (DateTime )value ;
            if (datetime != null)
            {
                writer.Write(convertDateToLong(datetime));
            }
        }

    }

    private long convertDateToLong(DateTime datetime)
    {
        DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        long ms = (long)(datetime - epoch).TotalMilliseconds;
        return ms;
    }
}

registering:

config.Formatters.Add(new DateTimeSerializer());

edit 2 :

current json :

{ "Id" : 1 , "Name" : "Sample Product" , "CreatedDate" : "2017-02-23T18:37:18.4218582+03:30" , "UpdatedDate" : "2017-02-23T18:37:18.4218582+03:30"}  

expected json :

{ "Id" : 1 , "Name" : "Sample Product" , "CreatedDate" : 432309482358723 , "UpdatedDate" : 432309482358723}
ReZa
  • 1,273
  • 2
  • 18
  • 33
  • What's wrong with what you have? – Chris Pratt Feb 23 '17 at 14:58
  • @ChrisPratt please see my edit – ReZa Feb 23 '17 at 15:04
  • Do you apply your config to the serializer? – CodeCaster Feb 23 '17 at 15:04
  • The defacto standard for dates in Json *is* ISO8601. Why long? What would it represent? – Panagiotis Kanavos Feb 23 '17 at 15:05
  • PS datetime was serialized as a Unix Timestamp in the Ajax days, but superceded by ISO8601. You can instruct Json.NET to use to old format with [DateFormatHandling.MicrosoftDateFormat](http://www.newtonsoft.com/json/help/html/DatesInJSON.htm) – Panagiotis Kanavos Feb 23 '17 at 15:08
  • @PanagiotisKanavos it is the equivalent of DateTime in milliseconds and the client needs it. – ReZa Feb 23 '17 at 15:09
  • Does it *have* to be relative to the epoch? If not, http://stackoverflow.com/questions/6156168/convert-datetime-to-long-and-also-the-other-way-around –  Feb 23 '17 at 15:10
  • @will yes it does – ReZa Feb 23 '17 at 15:12
  • @ReZa what does the client need exactly and why? Is the client unable to deal with the standard way of passing time? The reason ISO8601 is used is that it can be parsed directly by Javascript. – Panagiotis Kanavos Feb 23 '17 at 15:13
  • Possible duplicate of [How to convert a Unix timestamp to DateTime and vice versa?](http://stackoverflow.com/questions/249760/how-to-convert-a-unix-timestamp-to-datetime-and-vice-versa) –  Feb 23 '17 at 15:14
  • 4.6 has a method for this. If you're not using 4.6, then the answer on the dupe target should work for you. If not, [edit] and describe why. –  Feb 23 '17 at 15:14
  • @ReZa also consider that the Unix timestamp doesn't contain timezone offset information, while the standard format does. The client can get in serious trouble unless UTC is used everywhere – Panagiotis Kanavos Feb 23 '17 at 15:15
  • @PanagiotisKanavos the client is ready made – ReZa Feb 23 '17 at 15:17
  • @will i know how to convert to long . the problem is automatic conversion to long when serializing to json – ReZa Feb 23 '17 at 15:20
  • You're using json.net? Have you tried http://stackoverflow.com/questions/26667664/newtonsoft-json-custom-jsonconverter-deserialize-to-datetime-not-working –  Feb 23 '17 at 15:40
  • @Will that's it . thank you . should i delete the question ? – ReZa Feb 23 '17 at 15:54
  • No, but people can VTC as a duplicate of that question, which would be useful for future visitors. I already VTC and retracted my vote, so I can't do it again. I'm not sure if you can VTC yourself as a duplicate. If you can, go ahead and do it. Otherwise, you can leave this here, it's fine. –  Feb 23 '17 at 16:07

0 Answers0