如何获得UTC time
没有任何日期的组件?
当我尝试分配Date.UtcNow
给Date
变量时,出现以下异常:
时间值包含不允许的日期组件
我正在分配Date.UtcNow
给Date
第三方 DLL 中的属性。我不知道这是否是不同版本的 .NET 的问题,或者是否是 DLL 是用 C# 编写的并且我在 VB.NET 中使用它。我可以绕过它的唯一方法是使用Date.UtcNow.ToString
.
如果您只想要时间部分,则需要获取TimeOfDay
属性。这是一个TimeStamp
:
Dim currentTime As TimeSpan = DateTime.UtcNow.TimeOfDay
The error message you provided:
Time value contains a date component which is not permitted
Is not a standard message from any exception in the .Net framework. You said (in comments) that you are are using a third-party dll. The exception is likely raised in that dll.
Without knowing more details about this dll, there's not a whole lot of advice I can offer. I can make some assumptions though. You said you are doing something like this:
thirdPartyObject.Date = DateTime.UtcNow.ToString
If this is even compiling then the Date
property on the object is not of type DateTime
. It is either a string
or an object
.
You also said you tried:
thirdPartyObject.Date = DateTime.UtcNow
If this compiles and throws the exception you mentioned, then it cannot be a string
. So I conclude that it must be of type object
.
This is quite bizarre. The third party object has a property of type object
called Date
that only wants a time? Whomever designed this API must not have been thinking about usability!
As a super-wild-ass-guess, I would try something like this:
thirdPartyObject.Date = DateTime.MinValue + DateTime.UtcNow.TimeOfDay
Or maybe it does want a string, then try:
thirdPartyObject.Date = DateTime.UtcNow.ToString("HH:mm:ss")
If you can clarify what third-party object you are using, or what it's API looks like for the Date
property, then perhaps I can refine my answer.
Dim dt As Date = Now.ToUniversalTime.ToShortTimeString