【问题标题】:Servicestack converting timezone from UTC to any timezoneServicestack 将时区从 UTC 转换为任何时区
【发布时间】:2019-12-01 02:29:36
【问题描述】:
我了解到您对此不支持。但我想确保我没有遗漏任何东西。
我们有几种情况需要将保存的 UTC 日期转换为其他时区。在查询期间,最好在加载时自动从 UTC 转换为特定时区。保存时从 a 时区转换为 UTC。我知道通常你会在 UI 中执行此操作。但是我们有些情况下,用户会调用 API 并要求 CSV,我们需要它进行转换。有谁知道这在servicestack中是否可行。也许使用 JSConfig 值或数据验证器?
【问题讨论】:
标签:
c#
.net-core
servicestack
ormlite-servicestack
【解决方案1】:
我不知道在 ServiceStack 中是否可行,但您可以使用 AutoMapper 并创建一个简单的适配器来将数据库 (UTC) 中的表示转换为客户端的表示。
伪代码:
public class Foo
{
public DateTime FooDate { get; set; }
}
public static class TimeZoneAdapter
{
public Foo Map(Foo foo)
{
var map = Mapper.Map(foo);
map.FooDate = ConvertToLocalDateTime(map.FooDate);
return map;
}
}
// Use Map on the database objects.
var q = db.From<Foo>().Select(x => TimeZoneAdapter.Map(x));
List<Foo> results = db.Column<Foo>(q);
【解决方案2】:
首先DateTime 仅支持Utc, Local, Unspecified DateTime Kinds,因此无法在不捕获时区信息的DateTime 属性中表示特定的时区,您需要更改实际的日期时间值并指定使用@ 987654325@ DateTimeKind 因为使用其他任何东西都是骗人的。
DateTimeOffset 内置结构确实允许您使用 DateTime 值捕获 TimeZone 偏移量,如果您需要存储 DateTime 以及特定的 TimeZone 偏移量,则可以使用它。
但我建议不要尝试使用此自定义应用序列化逻辑配置序列化程序。正如@Dennis1679 所建议的那样,将此逻辑应用于后处理步骤中,例如在自定义映射器中。 ServiceStack.Text 确实支持 .NET 的 DataContract 的自定义钩子是在序列化之前/之后运行自定义逻辑的另一种选择,例如:
public class SerializationHooksExamples
{
/// Will be executed when deserializing starts
[OnDeserializing]
protected void OnDeserializing(StreamingContext ctx)
{
//...
}
/// Will be executed when deserializing finished
[OnDeserialized]
protected void OnDeserialized(StreamingContext ctx)
{
//...
}
/// Will be executed when serializing starts
[OnSerializing]
protected void OnSerializing(StreamingContext ctx)
{
//...
}
/// Will be executed when serializing finished
[OnSerialized]
protected void OnSerialized(StreamingContext ctx)
{
//...
}
}