How to Deserialize a Unix Timestamp (Μs) to a Datetime from JSON

How to deserialize a unix timestamp (μs) to a DateTime from JSON?

I cleaned up Cris's solution a tad and implemented WriteJson:

class Bookmark
{
public string title;
public long id;
[JsonConverter(typeof(MicrosecondEpochConverter))]
public DateTime dateAdded;
[JsonConverter(typeof(MicrosecondEpochConverter))]
public DateTime lastModified;
public string type;
public string root;
public long parent;
public List<Bookmark> children;
public string uri;

public override string ToString()
{
return string.Format("{0} - {1}", title, uri);
}
}

public class MicrosecondEpochConverter : DateTimeConverterBase
{
private static readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(((DateTime)value - _epoch).TotalMilliseconds + "000");
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null) { return null; }
return _epoch.AddMilliseconds((long)reader.Value / 1000d);
}
}

internal class Program
{

private static void Main(string[] args)
{
var jsonString = File.ReadAllText(@"T:/bookmarks-2013-11-13.json");
var rootMark = JsonConvert.DeserializeObject<Bookmark>(jsonString);
var ret = JsonConvert.SerializeObject(rootMark);
}
}

Deserialize timestamp value in JSON to DateTime while Model Binding

I found solution for this. I used ITypeConverter

// Converts timestamp to DateTime
public class DateTimeConverter : ITypeConverter<long?, DateTime?>
{
private readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public DateTime? Convert(long? source, DateTime? destination, ResolutionContext context)
{
if (!source.HasValue) return null;
return _epoch.AddSeconds(source.Value);
}
}

// Converts DateTime to Timestamp
public class TimeStampConverter : ITypeConverter<DateTime?, long?>
{
private readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public long? Convert(DateTime? source, long? destination, ResolutionContext context)
{
if (source == null) return null;
var result = (long)(source - _epoch).Value.TotalSeconds;
return result;
}
}

And I created a Map like this in startup.cs

AutoMapper.Mapper.Initialize(x =>
{
x.CreateMap<long?, DateTime?>().ConvertUsing<DateTimeConverter>();
x.CreateMap<DateTime?, long?>().ConvertUsing<TimeStampConverter>();
});

I used this couple of classes in my project and it is working fine. This may help anyone who is trying to achieve the same thing.

Deserialise Json Timestamp with System.Text.Json

You can register custom date formatters for System.Text.Json also.
https://learn.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support

public class DateTimeConverterForCustomStandardFormatR : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.UnixEpoch.AddMilliseconds(reader.GetInt64());
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
// The "R" standard format will always be 29 bytes.
Span<byte> utf8Date = new byte[29];

bool result = Utf8Formatter.TryFormat(value, utf8Date, out _, new StandardFormat('R'));
Debug.Assert(result);

writer.WriteStringValue(utf8Date);
}
}

string js = "{\"ServerTime\":1613967667240}";
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new DateTimeConverterForCustomStandardFormatR());
var value = JsonSerializer.Deserialize<ApiServerTime>(js, options);

How to deserialize date (milliseconds) with JSON.NET?

You can create a custom DateTime converter

var token = JsonConvert.DeserializeObject<TokenResponse>(response.Content, 
new MyDateTimeConverter());

public class MyDateTimeConverter : Newtonsoft.Json.JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var t = long.Parse((string)reader.Value);
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(t);
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

How to deserialize a unix timestamp (μs) to a DateTime from JSON?

I cleaned up Cris's solution a tad and implemented WriteJson:

class Bookmark
{
public string title;
public long id;
[JsonConverter(typeof(MicrosecondEpochConverter))]
public DateTime dateAdded;
[JsonConverter(typeof(MicrosecondEpochConverter))]
public DateTime lastModified;
public string type;
public string root;
public long parent;
public List<Bookmark> children;
public string uri;

public override string ToString()
{
return string.Format("{0} - {1}", title, uri);
}
}

public class MicrosecondEpochConverter : DateTimeConverterBase
{
private static readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(((DateTime)value - _epoch).TotalMilliseconds + "000");
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.Value == null) { return null; }
return _epoch.AddMilliseconds((long)reader.Value / 1000d);
}
}

internal class Program
{

private static void Main(string[] args)
{
var jsonString = File.ReadAllText(@"T:/bookmarks-2013-11-13.json");
var rootMark = JsonConvert.DeserializeObject<Bookmark>(jsonString);
var ret = JsonConvert.SerializeObject(rootMark);
}
}

Proper Way to Convert JSON Date to .NET DateTime During Deserialization

I found a simple answer. In my javascript, I was serializing the data using the JavaScriptSerializer. After much googling, I found this article that shows how to serialize using JsonConvert that causes a more .NET-friendly DateTime to be used.

Old:

var specs = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.JobSpecEquipment))

Dates look like this: Date(1348017917565)

New:

var specs = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.JobSpecEquipment));

Dates look like this: 2012-09-18T21:27:31.1285861-04:00

So the problem was really how I was serializing in the first place. Once I used JsonConvert, deserialization on the back end simply worked.

Using Newtonsoft.Json, what's the backing field for a property in a getter

If you aren't using "automatically implemented properties" (i.e. {get;set;}), then the backing field is whatever you create. It isn't done by the compiler. So: declare a field and use that.

Note that your set doesn't actually assign the computed value to anything currently - it just does the math and drops the value on the floor. That also needs to assign to the backing field.

I'll be honest though; I'm not sure why this isn't just:

[JsonProperty("date")]
public DateTime Date {get;set;}

It looks like you're trying to convert it such that it is DateTime in the serialization but epoch seconds inside the type. That sounds... unusual and odd. If you really want that, though, just declare an integer (long, presumably) for your field, and read/write accordingly.

Simplest way to convert UNIX Timestamp to DateTime in ASP.NET

Don't fight the format, just allow Timestamp to be a long. There's no reason you can't convert the Timestamp to whatever format you need by calling a property on the Sensor object.

public class Sensor
{
public long Id { get; set; }

[Required]
public string Tag { get; set; }

public long Timestamp { get; set; }

public DateTime TimestampDt
{
get
{
return DateTimeOffset.FromUnixTimeSeconds(Timestamp).UtcDateTime;
}
}

public string Status { get; set; }

public int Valor { get; set; }
}


Related Topics



Leave a reply



Submit