如何将整数值转换为日期时间 [英] How to convert integer value to datetime
问题描述
你好朋友
我想将整数值1转换为日期时间,然后将其与日期时间值相减.
我正在使用此代码
Hello Friends
I want to convert integer value 1 to convert it into datetime and then subtract it with a datetime value.
I am using this code
DateTime lasttime = LastUpdateTime - Convert.ToDateTime(1);
其中LastUpdateTime是DateTime类型变量.
给我一个错误
where LastUpdateTime is DateTime type variable.
It is giving me an error
Cannot implicitly convert type 'System.TimeSpan' to 'System.DateTime'.
谁能帮忙.
在此先感谢
Can any one help.
Thanks in advance
推荐答案
你好RashdSiddique
DateTime和TimeSpan似乎有些混乱.
Hello RashdSiddique
there seem to be confusion on DateTime and TimeSpan.
- DateTime是特定的时间点.
- TimeSpan是持续时间.
- 两点之间的差时间(DateTime)是持续时间(TimeSpan).
- 您不能将持续时间作为时间点.
- 您可以将持续时间添加到时间点以获得另一个时间点特定时间点.
- DateTime is a specific point in time.
- A TimeSpan is a duration.
- The difference between two points in time (DateTime) is a duration (TimeSpan).
- You cannot make a duration being a point in time.
- You can add a duration to a point in time to get another specific point in time.
使用DateTime类的几种Add...
方法之一来实现所需的结果.
请注意,添加负数等于减去该正数-这就是DateTime类没有Subtract...
方法的原因.
最后,Convert.ToDateTime(int)
对我来说似乎很奇怪.作为维护者,我不喜欢这样的代码,因为它是违反直觉的,并留下了一个关键问题:哪个单元?
干杯
Andi
Use one of the several Add...
methods of the DateTime class to accomplish the desired result.
Note that adding a negative amount equals to subtract that positive amount - that''s why the DateTime class has no Subtract...
methods.
Finally, the Convert.ToDateTime(int)
seems very odd to me. As a maintainer I would dislike such code, since it is anti-intuitively and leaves a crucial question open: what unit?
Cheers
Andi
使用
LastUpdateTime.AddDays(-1);
那里有两个问题:
1)您希望从Convert.ToDateTime(1)
作为日期时间组合得到什么?因为您将获得的只是运行时错误无效的从"Int32"转换为"DateTime"的转换."
"1"不是日期.
2)如果您减去两个日期,则不会得到日期-您会得到一个时间间隔. 明天减去上周二"会给您几天而不是日期.尝试使用TimeSpan来接收它.
您可能想做的是计算自上次更新以来的时间间隔:
There are two problems there:
1) What do you expect to get as a date time combination fromConvert.ToDateTime(1)
? Because all you will get is the run time error "Invalid cast from ''Int32'' to ''DateTime''."
"1" is not a date.
2) If you subtract two dates, you do not get a date - you get a time interval. "Tomorrow minus last Tuesday" will give you a number of days, not a date. Try using a TimeSpan to receive it instead.
What you are probably trying to do is work out the time interval since the last update:
TimeSpan ts = DateTime.Now - LastUpdateTime;
这篇关于如何将整数值转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!