JSON.NET์์ ๋ค์์ ์ํํ ์ ์์ต๋๋ค.
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
System.Text.Json
๋น์ทํ ๊ฒ์ด ์์ต๋๊น?
๊ธฐ๋ณธ๊ฐ์ ์ค์ ํ๋ ์ต์
์ด ์์ผ๋ฉด ์๋์ผ๋ก ์ ๋ฌํ ์ ์์ต๋๊น?
๋ํ ๊ธฐ๋ณธ๊ฐ( Local
, Utc
, Unspecified
)์ ๋ฌด์์
๋๊น?
cc @layomia on ๋ ์ง
DateTime์ ์ด๋ฌํ ๊ฐ ํ์(์: timezone\offset ํฌํจ ๋ฐ ์ ์ธ)์ผ๋ก ์ค์ ํ ์ ์์ผ๋ฏ๋ก ํ๋ ๊ธฐ\์์ฑ๊ธฐ(๋ฐ ์ง๋ ฌ ๋ณํ๊ธฐ)๋ ์ฌ์ฉ ๊ฐ๋ฅํ ๊ฒ์ ์ฌ์ฉํ๊ณ ISO 8601 ํ์์ ์ฌ์ฉํ์ฌ ์ด๋ฅผ ํํํ๋ค๊ณ ๊ฐ์ ํฉ๋๋ค.
@btecu ISO 8601 ํ๋กํ์ ์ง๋ ฌ ๋ณํ๊ธฐ์์ ๊ธฐ๋ณธ์ ์ผ๋ก ์ฌ์ฉ๋ฉ๋๋ค(์: 2019-07-26T16:59:57-05:00).
์ญ์ง๋ ฌํ๋ฅผ ์ํด datetime offset์ด "hh:mm"๋ก ์ฃผ์ด์ง๋ฉด DateTimeKind.Local
๊ฐ ์๋ DateTime์ด ์์ฑ๋ฉ๋๋ค. "Z"๋ DateTimeKind.Utc
ํฉ๋๋ค. ์คํ์
์ด ์ ๊ณต๋์ง ์์ผ๋ฉด DateTimeKind.Unspecified
๊ฐ ์๋ DateTime์ด ์์ฑ๋ฉ๋๋ค.
์ญ ๋งคํ์ ์ง๋ ฌํ์ ์ ์ฉ๋ฉ๋๋ค. DateTimeKind.Local
๋ฅผ ์ฌ์ฉํ์ฌ DateTime
๋ฅผ ์์ฑํ๋ฉด "hh:mm" ํ์์ ์คํ์
์ด ์๋ ISO ํํ์ด ์์ฑ๋๋ ์์
๋๋ค.
System.Text.Json์ DateTime ๋ฐ DateTimeOffset ์ง์๊ณผ ์ฌ์ฉ์ ์ง์ ๊ตฌ๋ฌธ ๋ถ์ ๋๋ ์์์ ๊ตฌํํ๋ ๋ฐฉ๋ฒ์ ๋ํ ์์ธํ ๋ด์ฉ์ https://docs.microsoft.com/en-us/dotnet/standard/datetime/system-text-json์ ์ฐธ์กฐ
@btecu ๋ถํํ๋ System.Text.Json
์์ ๋น์ทํ ์ต์
์ ์ฌ์ฉํ๋ ์ ์ผํ ๋ฐฉ๋ฒ์ ๋ค์์ ์ํํ๋ ๊ฒ์
๋๋ค.
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});
๊ทธ๋ฐ ์์ผ๋ก DateTimeConverter๋ฅผ ๊ตฌํํ์ญ์์ค.
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"));
}
}
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
@btecu ๋ถํํ๋
System.Text.Json
์์ ๋น์ทํ ์ต์ ์ ์ฌ์ฉํ๋ ์ ์ผํ ๋ฐฉ๋ฒ์ ๋ค์์ ์ํํ๋ ๊ฒ์ ๋๋ค.๊ทธ๋ฐ ์์ผ๋ก DateTimeConverter๋ฅผ ๊ตฌํํ์ญ์์ค.