简体   繁体   English

如何将C#日期时间值转换为UTC时区

[英]How to convert C# datetime value to UTC timezone

I am in need to pass value of type DateTime to an API in the below format 我需要以以下格式将DateTime类型的值传递给API

2018-12-02T07:00:00.000Z //required format

but the datetime value from Db I am getting is as 但是我从Db得到的datetime值是

2018-10-25 05:30:00.0000000

Now using the .ToString("o") , the value formatted as 现在使用.ToString("o") ,将值格式化为

2018-10-25T05:30:00.0000000

Checked below SO links 在下面检查SO链接

Where's the DateTime 'Z' format specifier? DateTime'Z'格式说明符在哪里?

http://stackoverflow.com/questions/9163977/converting-datetime-to-z-format http://stackoverflow.com/questions/9163977/converting-datetime-to-z-format

but not converting into the required format. 但不会转换为所需的格式。

My understanding is having Z in the datetime represents UtcTimeZone. 我的理解是在日期时间中使用Z表示UtcTimeZone。

Are you looking for something like this? 您是否正在寻找这样的东西?

var baseTime = DateTime.Parse("2018-10-25 05:30:00.0000000");
var utcTime = baseTime.ToUniversalTime();
Console.WriteLine(utcTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));

You can try it out here: https://dotnetfiddle.net/HsdMcu 您可以在这里尝试: https : //dotnetfiddle.net/HsdMcu

If you have summer and winter time in your region you might need to use a bit more sophisticated way for parsing your intial time correctly, this can be found in this answer . 如果您所在地区有夏季和冬季,则可能需要使用更复杂的方法来正确解析初始时间,可以在此答案中找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将毫秒转换为 UTC dateTime C# - How to convert millisecond to UTC dateTime C# 如何将日期时间转换为 c# 中的特定时区? - How to convert a datetime to specific timezone in c#? 如何将此 UTC 日期时间字符串转换为 DateTime object c# - How to convert this UTC datetime string to DateTime object c# 在C#中,将Sql Server 2005 datetime值转换为另一个时区 - In C#, convert Sql Server 2005 datetime value to another timezone 在 C# 中,如何始终将 DateTime 值视为在 DateTime 表示的时间是欧洲/伦敦的本地值,并将其转换为 UTC? - In C#, how can I always treat a DateTime value as being local to Europe/London at the time represented by the DateTime, and convert this to UTC? C# 将 UTC int 转换为 DateTime object - C# convert UTC int to DateTime object c#将UTC时间转换为中部,包括DateTime对象中的时区 - c# Converting UTC time to Central including timezone in DateTime object 如何将带有时区的ISO 8601转换为C#日期时间? - How to convert ISO 8601 with timezone to C# Datetime? 如何将带时区的 DateTime 转换为 Unix TimeStamp ? C# - How I can convert a DateTime with timezone to a Unix TimeStamp ? C# C# DateTimeInvalidLocalFormat - 如何将时区设置为 UTC - C# DateTimeInvalidLocalFormat - How to set timezone to UTC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM