C Sharp/Dates and Times

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] How to Use C# Dates and Times

C# dates and times are a powerful feature in the .NET framework. You can use this for date and time manipulation. It provides a very simple way to work with dates and times. Lets take a look at some real code.


Here is how you would use the datetime struct:

DateTime MyDate(year, month, day, hour, minute, second, millisecond);

The datetime class is overloaded with 12 other versions. So, you don't have to use the exxact same code that we have above.

We will now declare a datetime object. Then print it Example 1:

using System;
class Program
{
    static void Main()
    {
        int year = 2007;
        int month = 7;
        int day = 2;
        DateTime MyDate = new DateTime(year, month, day);
 
        //print date
        Console.WriteLine("The date is: ");
        Console.WriteLine(MyDate.Month + "/" + MyDate.Day + "/" + MyDate.Year);
        Console.Read();
    }
}

Output:

The date is:
7/2/2007


[edit] C# Datetime as a Long

The datetime class is a flexible one. You are also able to have a long represent a date. The long represents the amont of ticks from January 1, 0001 - 12AM. For example, if you want the date and time for the long 6725312194358 you can put this in the datetime constructor. Take a look below:


Example 2: This example will convert a long to a regular date and time

using System;
class Program
{
    static void Main()
    {
        DateTime MyDate = new DateTime(6725312194358);
 
        //print date
        Console.WriteLine("The date and time is: ");
        Console.WriteLine(MyDate.Month + "/" + MyDate.Day + "/" + MyDate.Year);
        Console.WriteLine(MyDate.Hour + ":" + MyDate.Minute + ":" + MyDate.Second);
        Console.Read();
    }
}

Output:

1/8/1
18:48:51

The date for this particular output is January 8, 0001 6:48pm and 51 seconds.

[edit] Convert a Long (Ticks) to a Datetime

Example 3: This example will convert a long to a datetime object

using System;
class Program
{
    static void Main()
    {
        long MyLongDate = 633189637786963557;
        DateTime MyDate = new DateTime(MyLongDate);
 
        //print date and time
        Console.WriteLine("The date is: ");
        Console.WriteLine(MyDate.Month + "/" + MyDate.Day + "/" + MyDate.Year);
        Console.WriteLine(MyDate.Hour + ":" + MyDate.Minute + ":" + MyDate.Second);
        Console.Read();
    }
}

Output:

7/2/2007
9:2:58

So the date and time is July 2, 2007 - 9:02AM 58 seconds


[edit] C# Datetime properties and Methods

We have given you the basics of how to use the datetime class. Now we will provide you with the datetime class and object reference


[edit] C# Convert a DateTime to a String

When using a DateTime object you can also convert it to a string by using the ToString() method. When you convert it to a string it will save as the format that is below.

12/21/2006 7:10:45 AM

The ToString() method returns the date and the time. The syntax to convert a datetime to a string is displayed below.

object.ToString(<format string>);


  • format string: This is the place where you want to specifiy your datetime format. C# is a powerful tool it will allow you to display the date and/or time in any format as you please.


To format your DateTime object here is a list of built-in formats that you can use. You must put the format character as a parameter in the ToString() method.


Character Format Display
d MM/dd/yyyy 04/01/2007
D dddd, MMMM, dd, yyyy Sunday, April 01, 2007
f dddd, MMMM, dd, yyyy HH:mm Sunday, April 01, 2007, 02:09 PM
F dddd, MMMM, dd, yyyy, HH:mm:ss Sunday, April 01, 2007, 02:09:05 PM
g MM/dd/yyy HH:mm 04/01/2007 02:09 PM
G MM/dd/yyyy HH:mm:ss 04/01/2007 02:09:05 PM
M or m MMMM dd April 01
R or r ddd,dd, MM yyyy HH:mm:ss GMT Sun, 01 Apr 2007 14:09:05 GMT
s yyyy - MM - dd T HH:mm:ss 2007-04-01T02:09:05
t HH:mm 02:09 PM
T HH:mm:ss 02:09:05 PM
U yyy-MM-dd HH:mm:ss Z 2007-04-01 02:09:05Z
Y or y yyyy, MMM April, 2007

Lets try some examples using the chart above

using System;
class Program
{
    static void Main()
    {
        DateTime date = DateTime.Now;
        Console.WriteLine(date.ToString("r"));
        Console.Read();
    }
}


using System;
class Program
{
    static void Main()
    {
        DateTime date = DateTime.Now;
        Console.WriteLine(date.ToString("f"));
        Console.Read();
    }
}

[edit] C# DateTime properties

These are all the datetime properties that are available to the .NET framework.

Property Description
Now Returns the current date and time on local computer
Today Returns current date from time from local computer and initializes time to 12:00AM midnight
UtcNow Returns the current date and time in Universal Coordinated Time.
Date Returns the date part of a datetime object and initializes the time part to 12:00AM
Day Returns an int which represents a certain day in a month (1 to 31)
DayOfWeek Returns a string which represents the day of the week (Sunday through Saturday) 
DayOfYear Returns an int from the datetime object which represents to day of the year (1 to 366)
Hour Returns the hour part of a datetime object
Kind N/A
Millisecond Returns an int which represents the  millisecond part of a datetime object(0 to 999)
Minute Returns an int which represents the  minute part of a datetime object (0 to 59)
Month Returns an int which represents the  month part of a datetime object (1 to 12)
Second Returns an int which represents the  second part of a datetime object (0 to 59)
Ticks

Returns a long which represents the ticks (100-nanosecond intervals) part of a datetime object which have elapsed since January 1, 0001 12:00:00 AM.

TimeOfDay

Returns a TimeSpan value which represents the interval that has already elapsed

since 12:00 AM
Year Returns the year part of a datetime object. (1 to 9999)

[edit] C# DateTime Methods

These are all the datetime methods that are available to the .NET framework

Method Description
Add Adds a timespan value
AddDays Adds a certain number of days
AddHours Adds a certain number of hours
AddMilliseconds Adds a certain number of Milliseconds
AddMinutes Adds a certain number of minutes
AddMonths Adds a certain number of months
AddSeconds Adds a certain number of seconds
AddTicks Adds a certain number of ticks
AddYears Adds a certain number of years
GetDateTimeFormats Returns a list of available datetime formats
GetHashCode Returns hashcode for a certain date. int is returned
IsDaylightSavingTime Determines if a datetime object is daylightsavings
Subtract Subtracts a timespan object from datetime object
ToBinary Serializes object to long value to be used later
ToFileTime Converts datetime to a windows file time
ToLocalTime Returns a local time object as datetime
ToLongDateString Returns a string as a longdate format
ToLongTimeString Returns a string as a long time format
ToOADate Converts a datetime object to a OLE automation date
ToShortDateString Returns a short date format
ToShortTimeString Returns a short time format
ToString Returns a string that represents the datetime object