MattDAVM
MattDAVM

Reputation: 515

Convert Time into Double

How may I get the "DateTime" function on a program and convert it into a double variable? My goal is to do some time operations like

(imagine that this variable t1 is a static "time" already written in a label) (now imagine that t2 is the DateTime from the computer)

t1 = 03:40:11
t2 = DateTime

t3 = t2 (that would be DateTime converted) + t1

How would I turn this DateTime into double so I can do this operation?

Upvotes: 0

Views: 4284

Answers (4)

MattDAVM
MattDAVM

Reputation: 515

I've done like RB and it worked, btw I've found what was missing for my program to do this kind of addition. I forgot to call a variable "DateTime" that would be "DateTime.Now" and I finished it doing:

  • dateTime = my variable which gets the time from the computer
  • timeSpan - my variable which has a static time number

    var finalTime = dateTime.Add(timeSpan).
    

Thank you guys for your help!

Upvotes: 0

Matthias
Matthias

Reputation: 37

There is no operator for adding two DateTime's. And since a DateTime is an absolute time value it would make much sense to add two absolute time values.

But you can do:

DateTime dt = DateTime.Now;
TimeSpan ts = TimeSpan.Parse("12:00:00");
DateTime dt1 = dt + ts;             // Adding a TimeSpan to a DateTime
TimeSpan ts1 = DateTime.Now - dt;   // Substracting two DateTimes

Upvotes: 0

Wojciech Kozaczewski
Wojciech Kozaczewski

Reputation: 326

Multiple operations are possible on raw TimeSpans. However, you can use it's TotalSeconds, TotalHours etc. propetries, which are double. Later, you can return to the TimeSpan world by TimeSpan.FromMinutes(m1 + m2 * 7.5).

Upvotes: 0

RB.
RB.

Reputation: 37182

You don't need to convert it into a double. You can perform arithmetic directly on the DateTime object:

var date = new DateTime(1944, 6, 6, 1, 10, 0);
var time = TimeSpan.Parse("03:40:11");

var newDate = date.Add(time);

Console.WriteLine(newDate); // Prints "06/06/1944 04:50:11"

Upvotes: 2

Related Questions