将时间跨度转换为日期时间 [英] Convert timespan to datetime

查看:144
本文介绍了将时间跨度转换为日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 private void button1_Click(object sender,EventArgs e)
{
TimeSpan a = new TimeSpan(12,00,00);
TimeSpan b =新TimeSpan(13,00,00);

TimeSpan r = b - a;
TimeSpan rr = new TimeSpan(r.Ticks / 2);

MessageBox.Show(Test\ n+ rr); ///这是类型TimeSpan

dateTimePicker.Value = Convert.ToDateTime(rr); ///错误附加信息:'System.TimeSpan'类型的对象无法转换为'System.IConvertible'类型。
}





我尝试过:



 dateTimePicker.Value = Convert.ToDateTime(rr); 









c# - 将DateTime转换为TimeSpan - 堆栈溢出 [ ^ ]





在IDE上试用

解决方案

你不能将Timespan转换为DateTime:这不起作用,因为这不是一个合乎逻辑的行动。想一想:如果我要求你在加6小时30分钟见到我,那是什么意思?没什么 - 除非它被理解为它有一个相对的起点。在正常谈话方面,我会在三十分钟内见到你很好 - 所有各方都明白这意味着从现在开始三十分钟,但如果没有这种理解,我们都会错过预约。



在计算方面,您可以非常轻松地包括当前时间:

 TimeSpan a = new TimeSpan(12,00,00); 
DateTime dt = DateTime.Now + a;

但你不能指望TimeSpan直接转换。


你不能将时间跨度转换为日期时间。



您可以将跨度添加到特定日期时间(例如当前时间)。



如果跨度总是正数且不到24小时,您只能使用DateTimePicker(参见如何:使用DateTimePicker控件显示时间| Microsoft Docs [ ^ ])通过相应地获取和设置时间成员。 />


否则你可以使用UpDown控件,自己创建或搜索网页。



一个例子可能是 Time Picker [ ^ ]。

private void button1_Click(object sender, EventArgs e)
{
    TimeSpan a = new TimeSpan(12, 00, 00);
    TimeSpan b = new TimeSpan(13, 00, 00);

    TimeSpan r = b - a;
    TimeSpan rr = new TimeSpan(r.Ticks / 2);

    MessageBox.Show("Test\n " + rr);   ///this is type TimeSpan

    dateTimePicker.Value =Convert.ToDateTime(rr);   /// ERROR" Additional Information: An object of type 'System.TimeSpan' can not be converted to type 'System.IConvertible'. "
}



What I have tried:

dateTimePicker.Value =Convert.ToDateTime(rr);



and

c# - Convert DateTime to TimeSpan - Stack Overflow[^]


Try it on your IDE

解决方案

You can't convert a Timespan to a DateTime: that doesn't work because it's not a logical action. Think about it: If I ask you to meet me at "plus 6 hours 30 minutes" what does that mean? Nothing - unless it's understood that there is a starting point for it to be relative to. In terms of normal conversation, "I'll meet you in thirty minutes" is fine - it's understood by all parties that that means "thirty minutes from now" but without that understanding we will all miss the appointment.

In computing terms you can include the current time very easily:

TimeSpan a = new TimeSpan(12, 00, 00);
DateTime dt = DateTime.Now + a;

But you can't expect a TimeSpan to convert directly.


You can not convert a time span to a datetime.

You might add the span to a specific datetime (e.g. the current time).

If the span is always positive and less than 24 hours, you can use the DateTimePicker with the time only (see How to: Display Time with the DateTimePicker Control | Microsoft Docs[^]) by getting and setting the time members accordingly.

Otherwise you can use an UpDown control, create your own or search the web.

An example might be the Time Picker[^].


这篇关于将时间跨度转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆