views:

3199

answers:

3

I've got the following class:

[DataContractAttribute]
public class TestClass
{
  [DataMemberAttribute]
  public DateTime MyDateTime { get; set; }
}

Here's the JSON:

{ "MyDateTime":"1221818565" }

The JSON is being returned from a PHP webservice.

What I need to do, is convert that epoch string into a valid C# DateTime. What's the best way of doing this?

I can do this:

[IgnoreDataMemberAttribute]
public DateTime MyDateTime { get; set; }

[DataMemberAttribute(Name = "MyDateTime")]
public Int32 MyDateTimeTicks
{
  get { return this.MyDateTime.Convert(...); }
  set { this.Created = new DateTime(...); }
}

But the trouble with this is, the MyDateTimeTicks is public (changing it to private causes an exception in the serialization process)

+2  A: 

Here's what I've come up with. In C#, it looks like you need to create a new DateTime and add the epoch value as 'seconds' to this DateTime. Here's what it looks like in code:

new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(1221818565);

When using the Visual Studio immediate window, I printed the result of this operation to the debugger console:

{9/19/2008 10:02:45 AM}
    Date: {9/19/2008 12:00:00 AM}
    Day: 19
    DayOfWeek: Friday
    DayOfYear: 263
    Hour: 10
    Kind: Unspecified
    Millisecond: 0
    Minute: 2
    Month: 9
    Second: 45
    Ticks: 633574153650000000
    TimeOfDay: {10:02:45}
    Year: 2008
Dan Esparza
You should also specify DateTimeKind.Utc.
dalle
+1  A: 

What you want is the following:

DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
DateTime dotnetTime = unixEpoch.AddSeconds(Convert.ToDouble(ticks));

where ticks is the value passed to you by PHP.

ageektrapped
+3  A: 

Finishing what you posted, AND making it private seemed to work fine for me.

[DataContract]
public class TestClass
{

    private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

    [IgnoreDataMember]
    public DateTime MyDateTime { get; set; }

    [DataMember(Name = "MyDateTime")]
    private int MyDateTimeTicks
    {
        get { return (int)(this.MyDateTime - unixEpoch).TotalSeconds; }
        set { this.MyDateTime = unixEpoch.AddSeconds(Convert.ToInt32(value)); }
    }

}
TheSoftwareJedi
Is that in Silverlight or .net / WPF?
Mark Ingram
it's standard .net wcf. should work in either
TheSoftwareJedi