Click here to Skip to main content
15,031,208 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
C#
DateTime lasttime = LastUpdateTime - Convert.ToDateTime(1);

where LastUpdateTime is DateTime type variable.
It is giving me an error
C#
Cannot implicitly convert type 'System.TimeSpan' to 'System.DateTime'.

Can any one help.

Thanks in advance
Posted
Updated 26-Jan-12 23:44pm
v2
Comments
Anuja Pawar Indore 27-Jan-12 5:45am
   
Added pre tag
BillWoodruff 27-Jan-12 10:00am
   
In this type of question the intent of what you mean by "subtract it" is unclear: you leave it up to our imaginations to assume that you mean subtract one day, one hour, one ?

Please try to be very specific: tell us what the integer value #1 means in this question.

Hello RashdSiddique

there seem to be confusion on DateTime and TimeSpan.

  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.


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
   
v3
Comments
BillWoodruff 27-Jan-12 9:58am
   
+5 Very nice comprehensive summary ! One very small suggestion: use "to get another specific point in time" in point #5.
Andreas Gieriet 27-Jan-12 10:39am
   
Thanks for your 5 and your suggestion for improvement!
Cheers
Andi
use
C#
LastUpdateTime.AddDays(-1);
   
v2
Comments
Anuja Pawar Indore 27-Jan-12 5:45am
   
Added pre tag
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:
C#
TimeSpan ts = DateTime.Now - LastUpdateTime;
   
Convert.ToDateTime(integer) is not supported.
Have a look at this[^] documentation.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900