是否可以使用Json.NET将DateTimeOffset序列化为zulu时间字符串? [英] Is it possible to serialize DateTimeOffset to zulu time string with Json.NET?

查看:80
本文介绍了是否可以使用Json.NET将DateTimeOffset序列化为zulu时间字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DateTimeOffset对象为"05/06/2014 05:54:00 PM -04:00".

I have a DateTimeOffset object of "05/06/2014 05:54:00 PM -04:00".

使用Json.NET和ISO设置进行序列化时,我得到"2014-05-06T17:54:00-04:00".

When serializing using Json.NET and ISO setting, I get "2014-05-06T17:54:00-04:00".

我想要的是字符串"2014-05-06T21:54:00Z"的UTC/Zulu版本.

What I would like to have is the UTC/Zulu version of that string "2014-05-06T21:54:00Z".

但是,我找不到任何序列化程序设置来实现此目的.我知道对于DateTime序列化,我可以将DateTimeZoneHandling = DateTimeZoneHandling.Utc设置为Zulu格式.但是,DateTimeOffset没有这样的设置选项.我想念什么吗?还是我必须为此创建一个自定义替代?

However, I could not find any serializer setting to achieve this. I know for DateTime serialization, I can set DateTimeZoneHandling = DateTimeZoneHandling.Utc to have the Zulu format. However, there isn't such setting option for DateTimeOffset. Am I missing something? Or do I have to create a custom override for this?

推荐答案

尝试使用Json.Net随附的IsoDateTimeConverter:

Try using the IsoDateTimeConverter that comes with Json.Net:

var date = new DateTime(2014, 5, 6, 17, 24, 55, DateTimeKind.Local);
var obj = new { date = new DateTimeOffset(date) };

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new IsoDateTimeConverter 
{ 
    DateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ", 
    DateTimeStyles = DateTimeStyles.AdjustToUniversal 
});

string json = JsonConvert.SerializeObject(obj, settings);
Console.WriteLine(json);

输出:

{"date":"2014-05-06T22:24:55Z"}

这篇关于是否可以使用Json.NET将DateTimeOffset序列化为zulu时间字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆