Anders Jensen
Anders Jensen

Reputation: 209

DateTime AddMinutes method not working

The purpose of my method is to get the currentTime, and set it back for 20 minutes. For what I can see, my method is correct, but the output shows something else.

This i my code:

DateTime currentTime = DateTime.Now;
double minuts = -20;
currentTime.AddMinutes(minuts);

Console.WriteLine("Nuværende tid: "+currentTime);

The output are as followed:

25-11-2011 14:01:54

My result should be:

25-11-2011 13:41:54.

Thanks!

Upvotes: 14

Views: 33912

Answers (6)

Dean McCoy
Dean McCoy

Reputation: 133

currentTime = DateTime.Now.AddMinutes(5.0f);

Upvotes: -1

dknaack
dknaack

Reputation: 60486

Description

The AddMinutes function returns a DateTime.

DateTime.AddMinutes Method Returns a new DateTime that adds the specified number of minutes to the value of this instance.

Sample

DateTime currentTime = DateTime.Now;
double minuts = -20;
currentTime = currentTime.AddMinutes(minuts);

Console.WriteLine("Nuværende tid: "+currentTime);

More Information

Upvotes: 43

HCL
HCL

Reputation: 36775

...
currentTime = currentTime.AddMinutes(minuts); 
...

Upvotes: 4

Alex Norcliffe
Alex Norcliffe

Reputation: 2489

DateTime is "immutable", what that means is you can never modify an existing instance, only make new ones. Strings are the same, for example. So you need to use the result of the AddMinutes call, which gives you your existing currentTime with the minuts variable applied.

currentTime = currentTime.AddMinutes(minuts);

Upvotes: 3

ChrisF
ChrisF

Reputation: 137148

AddMinutes returns a new DateTime object so you need:

    DateTime currentTime = DateTime.Now;
    double minuts = -20;
    DateTime newTime = currentTime.AddMinutes(minuts);

    Console.WriteLine("Nuværende tid: "+newTime);

Upvotes: 2

doblak
doblak

Reputation: 3136

try:

currentTime = currentTime.AddMinutes(minuts);

Upvotes: 4

Related Questions