且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将整数值转换为日期时间

更新时间:2023-02-03 15:40:29

你好RashdSiddique

DateTime和TimeSpan似乎有些混乱.
Hello RashdSiddique

there seem to be confusion on DateTime and TimeSpan.

  1. DateTime是特定的时间点.
  2. TimeSpan是持续时间.
  3. 两点之间的差时间(DateTime)是持续时间(TimeSpan).
  4. 您不能将持续时间作为时间点.
  5. 您可以将持续时间添加到时间点以获得另一个时间点特定时间点.

  1. DateTime is a specific point in time.
  2. A TimeSpan is a duration.
  3. The difference between two points in time (DateTime) is a duration (TimeSpan).
  4. You cannot make a duration being a point in time.
  5. 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 from Convert.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;