[C#] 将UTC时间字串转换为DateTime

332 阅读1分钟

为建立中文知识库加块砖        ——中科大胡不归

问题描述

在C#中,如何将形如“2022-05-16T14:10:12+08:00”的UTC格式的时间字串转化为DateTime类型?

解决方法

const string utc = "2012-03-20T14:18:25.000+04:00";
var dto = DateTimeOffset.Parse(utc);

//Get the date object from the string. 
var dt = dto.DateTime; 

//Get DayOfWeek in chinese
var week = CultureInfo.GetCultureInfo("zh-CN").DateTimeFormat.GetDayName(dt.DayOfWeek);

//Convert the DateTime to string. 
Console.WriteLine(dt.ToString($"MM月dd日 {week}"));

效果演示

参考文章

  1. how to convert date with 'T' to/from string in C#