C Sharp/DateTime/AddSeconds

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables
C# - Operators
C# - Flow Control
C# - Variables II
C# - Functions and Methods
C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application

Contents

[edit] Using the DateTime.AddSeconds Method

To use the DateTime.AddSeconds method you will not specify a timespan. You must specify the amount of seconds you want to add. It accepts a double value so it can calculate partial seconds. Remember, a timespan must NOT be used with DateTime.AddSeconds.


[edit] Syntax

DateTime.AddSeconds(<double>)

[edit] Example 1:

using System;
class Program
{
    static void Main()
    {
        DateTime today = DateTime.Now;
 
        Console.WriteLine("today: " + today.ToString());
        today = today.AddSeconds(11);
        Console.WriteLine("New Date: " + today.ToString());
        Console.Read();
    }
}

Output:

today: 4/5/2007 8:28:51 PM
New Date: 4/5/2007 8:29:02 PM


As you can see the AddSeconds method simply added 11 seconds to the current date.

[edit] Example 2:

This example will add partial seconds. We will include the milliseconds part to show that adding a partial second works.

using System;
class Program
{
    static void Main()
    {
        DateTime today = DateTime.Now;
 
        Console.WriteLine("Date: " + today.ToString() + " and " +
                            today.Millisecond.ToString() + "ms");
        today = today.AddSeconds(11.3);
        Console.WriteLine("New Date: " + today.ToString() + " and " +
                            today.Millisecond.ToString() + "ms");
        Console.Read();
    }
}

Output:

today: 4/5/2007 9:02:22 PM and 187ms
New Date: 4/5/2007 9:02:31 PM and 487ms

As you can see the program added a partial second and it also adjusted the milliseconds part.



<-- DateTime Tutorial