简体   繁体   English

如何将日期转换为毫秒(UTC),反之亦然?

[英]How to convert date to ms (UTC) and vice-versa?

I'm making a C# windows form application.我正在制作一个 C# windows 窗体应用程序。 There is a DateTimePicker tool on the application and the tool's format is MM/dd/yyyy hh:mm:ss tt.应用程序上有一个 DateTimePicker 工具,该工具的格式为 MM/dd/yyyy hh:mm:ss tt。 For example, the date looks like this on the application: 07/28/2021 09:10:50 AM例如,应用程序上的日期如下所示:07/28/2021 09:10:50 AM

I want to convert that date to milliseconds depending on UTC, and send that milliseconds to the server.我想根据UTC将该日期转换为毫秒,并将该毫秒发送到服务器。 I also need to do the opposite.我也需要做相反的事情。 When I receive the milliseconds from the server (UTC), I need to convert it to the format of the DateTimePicker (MM/dd/yyyy hh:mm:ss tt).当我从服务器 (UTC) 收到毫秒时,我需要将其转换为 DateTimePicker (MM/dd/yyyy hh:mm:ss tt) 的格式。 I don't need to convert the date to the local time when I receive the milliseconds from the server.当我从服务器接收毫秒数时,我不需要将日期转换为本地时间。 Everything will depend on UTC.一切都取决于UTC。 How can I do that?我怎样才能做到这一点?

Use ParseExact to parse a specific format https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?redirectedfrom=MSDN&view=net-5.0#overloads使用 ParseExact 解析特定格式https://docs.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?redirectedfrom=MSDN&view=net-5.0#overloads

Be aware that depending on the tool/version using to accept the datetime, it may assume local-time/UTC so you may want to check the DateTime.Kind property.请注意,根据用于接受日期时间的工具/版本,它可能假定为本地时间/UTC,因此您可能需要检查 DateTime.Kind 属性。 https://github.com/dotnet/aspnetcore/issues/11584 https://github.com/dotnet/aspnetcore/issues/11584

If you are having trouble leverage DateTimeOffset to accept the value from the server and then pull out the raw DateTime from there using:如果您在利用 DateTimeOffset 接受来自服务器的值时遇到问题,然后使用以下方法从那里提取原始 DateTime:

DateTimeOffset.DateTime

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM