laatzen/Common/LaaProduction/Einheiten.cs
2023-08-25 15:23:57 +02:00

80 lines
2.2 KiB
C#

namespace LaaProduction
{
using Newtonsoft.Json;
using System;
[JsonConverter(typeof(TimeJsonConverter))]
public class Time
{
public double Seconds { get; set; }
public double Minutes
{
get => this.Seconds / 60;
set => this.Seconds = value * 60;
}
public double Hours
{
get => this.Minutes / 60;
set => this.Minutes = value * 60;
}
public static implicit operator double(Time time)
=> time.Seconds;
public static implicit operator Time(double miliseconds)
=> new Time { Seconds = miliseconds };
public static implicit operator byte[](Time time)
=> BitConverter.GetBytes(time.Seconds);
public static implicit operator Time (byte[] bytes)
=> BitConverter.ToDouble(bytes, 0);
}
public class TimeJsonConverter : JsonConverter<Time>
{
public override bool CanRead => true;
public override bool CanWrite => true;
public override Time ReadJson(JsonReader reader, Type objectType, Time existingValue, Boolean hasExistingValue, JsonSerializer serializer)
{
while (reader.ValueType != typeof(double))
{
reader.Read();
}
if (reader.Value is double value)
{
return value;
}
return default(double);
}
public override void WriteJson(JsonWriter writer, Time value, JsonSerializer serializer)
{
writer.WriteValue(value?.Seconds);
}
//public override bool CanConvert(Type objectType)
// => objectType == typeof(Time) || objectType == typeof(double);
//public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
//{
// throw new NotImplementedException();
//}
//public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
//{
// if (value is Time time)
// {
// writer.WriteValue(time.Seconds);
// }
//}
}
}