C# 将日期时间转换为时间跨度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17959440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert DateTime to TimeSpan
提问by Ayoub.A
I want to convert a DateTime
instance into a TimeSpan
instance, is it possible?
我想把一个DateTime
实例转换成一个TimeSpan
实例,可以吗?
I've looked around but I couldn't find what I want, I only find time difference. More specifically, I want to convert a DateTime
instance into milliseconds, to then save it into an IsolatedStorage.
我环顾四周,但找不到我想要的东西,我只能找到时差。更具体地说,我想将一个DateTime
实例转换为毫秒,然后将其保存到一个独立存储中。
采纳答案by MiMo
To convert a DateTime
to a TimeSpan
you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime
value (and add it when you want to convert back to DateTime
).
要将 a 转换DateTime
为 a,TimeSpan
您应该选择一个基准日期/时间 - 例如 2000 年 1 月 1 日午夜,然后从您的DateTime
值中减去它(并在您想转换回 时添加它DateTime
)。
If you simply want to convert a DateTime
to a number you can use the Ticks
property.
如果您只是想将 a 转换DateTime
为数字,则可以使用该Ticks
属性。
回答by NoOne
In case you are using WPF and Xceed's TimePicker (which seems to be using DateTime?) as a timespan picker -as I do right now- you can get the total milliseconds (or a TimeSpan) out of it like so:
如果您使用 WPF 和 Xceed 的 TimePicker(似乎在使用 DateTime?)作为时间跨度选择器 - 就像我现在所做的那样 - 您可以像这样获得总毫秒数(或 TimeSpan):
var milliseconds = DateTimeToTimeSpan(timePicker.Value).TotalMilliseconds;
TimeSpan DateTimeToTimeSpan(DateTime? ts)
{
if (!ts.HasValue) return TimeSpan.Zero;
else return new TimeSpan(0, ts.Value.Hour, ts.Value.Minute, ts.Value.Second, ts.Value.Millisecond);
}
XAML :
XAML:
<Xceed:TimePicker x:Name="timePicker" Format="Custom" FormatString="H'h 'm'm 's's'" />
If not, I guess you could just adjust my DateTimeToTimeSpan() so that it also takes 'days' into account or do sth like dateTime.Substract(DateTime.MinValue).TotalMilliseconds
.
如果没有,我想你可以调整我的 DateTimeToTimeSpan() 以便它也考虑“天”或做某事dateTime.Substract(DateTime.MinValue).TotalMilliseconds
。
回答by KoalaBear
TimeSpan.FromTicks(DateTime.Now.Ticks)
回答by KoalaBear
You can just use the TimeOfDay property of date time, which is TimeSpan type:
您可以只使用日期时间的 TimeOfDay 属性,即 TimeSpan 类型:
DateTime.TimeOfDay
This property has been around since .NET 1.1
此属性自 .NET 1.1 以来一直存在
More information: http://msdn.microsoft.com/en-us/library/system.datetime.timeofday(v=vs.110).aspx
更多信息:http: //msdn.microsoft.com/en-us/library/system.datetime.timeofday(v=vs.110).aspx
回答by Muhammad Awais
Try the following code.
试试下面的代码。
TimeSpan CurrentTime = DateTime.Now.TimeOfDay;
Get the time of the day and assign it to TimeSpan
variable.
获取一天中的时间并将其分配给TimeSpan
变量。