简体   繁体   English

如何将日期时间转换为双倍 c#

[英]How to convert date time to double c#

I'm trying to convert a date and time value from a JSON string to a double in C#, but I keep getting the below error.我正在尝试将日期和时间值从 JSON 字符串转换为 C# 中的双精度值,但我不断收到以下错误。 在此处输入图像描述

Below is the code i am trying to debug.下面是我要调试的代码。

 DateTime baseDate = DateTime.SpecifyKind(DateTime.Parse("1970-01-01"), DateTimeKind.Utc);
 docRoot.scheduleDate = baseDate.AddSeconds((double)docRoot.scheduleDate);

I understand what the error is saying but I've been having a difficult time finding a workaround.我明白错误在说什么,但我一直很难找到解决方法。 I've tried the approach below but havent succeeded.我尝试了下面的方法,但没有成功。

  1. Converting docRoot.scheduleDate to a string, then trying to convert the string to a double using Convert.ToDouble(stringScheduleDate) .docRoot.scheduleDate转换为字符串,然后尝试使用Convert.ToDouble(stringScheduleDate)将字符串转换为双精度。 The only issue here is that the special characters in the docRoot.scheduleDate ("10/10/2019 08:29:30") are causing a format error.这里唯一的问题是docRoot.scheduleDate ("10/10/2019 08:29:30") 中的特殊字符导致格式错误。

I believe that if i remove the special characters i'll resolve the issue.我相信,如果我删除特殊字符,我会解决问题。 But i'm wondering if there is a different approach to getting past this exception?但我想知道是否有不同的方法来克服这个异常?

Converting to a string then removing the special characters seems a bit inefficient in my opinion, so if anyone is willing to contribute some other ideas I much appreciate it.在我看来,转换为字符串然后删除特殊字符似乎效率低下,所以如果有人愿意贡献一些其他想法,我将不胜感激。

You should be able to get the Ticks to double very easily:你应该能够很容易地让 Ticks 翻倍:

docRoot.scheduleDate = baseDate.AddSeconds((double)docRoot.scheduleDate.Second);

I just realized this was for an add seconds method, this will work better我刚刚意识到这是一个添加秒的方法,这会更好

Also of note.也值得注意。 The OADate internally uses a private InternalTicks property too. OADate 在内部也使用私有 InternalTicks 属性。 So that could also cause issues.所以这也可能导致问题。

Use DateTime.ToOADate to get a decimal representation as per https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tooadate and DateTime.FromOADate to deserialize.使用DateTime.ToOADate根据https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tooadateDateTime.FromOADate获取十进制表示以反序列化。

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

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