Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Using the DateTime object

This tutorial shows you how to use the .NET object DateTime: how to get the current date and time, how to filter the output, check for leap years, find the number of days in a given month, add and subtract time to the current date and time.

On Sunday, September 19th 2004 at 03:13 AM
By Andrew Pociu (View Profile)
*****   (Rated 4.5 with 42 votes)
Contextual Ads
More C# Resources
Advertisement
Here you'll see some examples of how to use the DateTime object.

The range of DateTime


DateTime has quite a range. It starts from January 1st, year 1, hour 12:00:00 and ends in year 9999, December 31st at 11:59:59 PM. So you don't have to worry unless your application won't be updated until the year 9999 .

Get the current date and time


That's what the DateTime object is used most of the time.

You can test the following code in a Console application.





Console.WriteLine("Current date and time: {0}", System.DateTime.Now);

Console.WriteLine("Current date: {0}", System.DateTime.Today);



Here's my output:





Current date and time: 9/18/2004 7:23:09

Current date: 9/18/2004 12:00:00

Press any key to continue



As expected, using DateTime.Now you'll get the current date and time of the machine on which the code runs.

Using DateTime.Today you get only the current exact date, but not the time which is always set to 12:00:00.

9/18/2004 6:03:07 uses the American date format system. It's straightforward that 9 represents the month (September) and 18 is the day.

Outputing current second, minute, hour...


Maybe you want to greet the user depending on the hour so you only need DateTime to provide you with the current hour on the user's machine.

You can easily retrieve only what interests you (current year, day of year...) with the DateTime object. The following code outputs information provided by DateTime separately:





System.DateTime dt = System.DateTime.Now;

// The number of ticks

Console.WriteLine("Ticks: {0}", dt.Ticks);

// The current year

Console.WriteLine("Year: {0}", dt.Year);

// The day of the year

Console.WriteLine("DayOfYear: {0}", dt.DayOfYear);

// The current month

Console.WriteLine("Month: {0}", dt.Month);

// The day of the week (0 = Sunday)

Console.WriteLine("DayOfWeek: {0}", dt.DayOfWeek);

// The current day

Console.WriteLine("Day: {0}", dt.Day);

// The current hour

Console.WriteLine("Hour: {0}", dt.Hour);

// The current minute

Console.WriteLine("Minute: {0}", dt.Minute);

// The current second

Console.WriteLine("Second: {0}", dt.Second);

// The current millisecond

Console.WriteLine("Millisecond: {0}", dt.Millisecond);



Here's the output I got:





Ticks: 632311327386856160

Year: 2004

DayOfYear: 262

Month: 9

DayOfWeek: Saturday

Day: 18

Hour: 19

Minute: 32

Second: 18

Millisecond: 685

Press any key to continue



Ticks represent the number of ticks since January 1st, year 1, hour 12:00 (midnight). One tick equals 100 nanoseconds.

Check for leap year


No need to create a function which calculates to see if one year is a leap year because now you have IsLeapYear() which returns true if it is a leap year and false if it isn't.





Console.WriteLine("Is 2005 a leap year? {0}", System.DateTime.IsLeapYear(2005));



2005 isn't a leap year so we'll get the answer False in the console. If you want to see if the current year is a leap year use the following combination:





Console.WriteLine("Is this year a leap year? {0}", System.DateTime.IsLeapYear(System.DateTime.Now.Year));



I'm running this in 2004, and IsLeapYear() returns true because 2004 is indeed a leap year.

How many days does this month have?


You'll often need to know the number of days the current month has, and since February 'varies' this proves useful. Here's how you obtain the number of days in the current month and current year:





Console.WriteLine("Days in this month: {0}", System.DateTime.DaysInMonth(System.DateTime.Now.Year, System.DateTime.Now.Month));



Adding time to the current date and time


In other programming languages when you had to add a few hours, or even a few seconds to a date/time you had to create an entire algorithm. It wasn't simple at all. Thanks to .NET you benefit of AddHours, AddMinutes, AddSeconds etc. methods.

Here's an example where seconds, minutes, days and months are added to the current date.





Console.WriteLine("Current date and time: {0}", System.DateTime.Now);

Console.WriteLine("Added 15 seconds: {0}", System.DateTime.Now.AddSeconds(15));

Console.WriteLine("Added 32 minutes: {0}", System.DateTime.Now.AddMinutes(32));

Console.WriteLine("Added 8 days: {0}", System.DateTime.Now.AddDays(8));

Console.WriteLine("Added 5 months: {0}", System.DateTime.Now.AddMonths(5));



This is how the output looks on my computer:





Current date and time: 9/18/2004 9:29:33

Added 15 seconds: 9/18/2004 9:29:48

Added 32 minutes: 9/18/2004 10:01:33

Added 8 days: 9/26/2004 9:29:33

Added 5 months: 2/18/2005 9:29:33

Press any key to continue



Look at the result after adding 5 months to the date. Things work properly and we jump in the year 2005, February 18.

Subtracting time from the current date and time


You subtract time by adding negative values. That means you still use the methods AddHours, AddMinutes, AddSeconds etc.





Console.WriteLine("Current date and time: {0}", System.DateTime.Now);

Console.WriteLine("Subtracted 15 seconds: {0}", System.DateTime.Now.AddSeconds(-15));

Console.WriteLine("Subtracted 32 minutes: {0}", System.DateTime.Now.AddMinutes(-32));

Console.WriteLine("Subtracted 8 days: {0}", System.DateTime.Now.AddDays(-8));

Console.WriteLine("Subtracted 5 months: {0}", System.DateTime.Now.AddMonths(-5));



Here's the result I got on this Sunday morning:





Current date and time: 9/19/2004 10:07:11

Subtracted 15 seconds: 9/19/2004 10:06:56

Subtracted 32 minutes: 9/19/2004 9:35:11

Subtracted 8 days: 9/11/2004 10:07:11

Subtracted 5 months: 4/19/2004 10:07:11

Press any key to continue
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by sdf on Thursday, February 24th 2005 at 08:04 AM

sdf

by Scott on Monday, May 8th 2006 at 12:11 AM

Helpfull, keep up the good work.

by Darryl Wright on Friday, May 12th 2006 at 10:56 AM

How do find the difference in time between two dates? I'm trying to check the time that has elapsed from the date a person signed in to there next sign in.

by Eddy on Wednesday, May 24th 2006 at 10:24 AM

Darryl, you could probably do it by subtracting the days of year. It\'s a property of System.Datetime. For example January 1st is day of year: 1, and febuary 1st is day of year: 32. If years are involved then just parse out the years and subtract those too.

by prathibha on Thursday, October 5th 2006 at 03:47 AM

hi,
its good.
i want to know how can we get the current time without the date.
pls help me

by yogarajan on Friday, April 27th 2007 at 02:46 AM

Hi
it is great ya
i have one doubt
if i give month in number the output will be full month name
ex:
input 9 => output September
input 7 => output July

by Renuka on Monday, May 14th 2007 at 01:02 AM

Hi!,
Nice work.
I want to know that how will u calculate how many weeks are there in a given month.

by keshav kamat on Monday, August 6th 2007 at 06:44 AM

Too good dude, this is very simple to understand and very effective for further improvement. Nice work. keep it up.

by parul on Saturday, February 2nd 2008 at 05:19 AM

nicely done...keep it up

by Ritu on Tuesday, July 15th 2008 at 05:40 AM

Hi,

Is it possible to dispose the DateTime object once I'm done using it? I'm working with limited memory so I need to free up the memory space once I'm done using the object.

Thanks in advance
Ritu

by yiwei on Monday, August 24th 2009 at 05:55 AM

thanx you!!!!!!!!!!!!!!!!!!!!!!!!!!

by GM on Tuesday, October 13th 2009 at 12:32 PM

that very gud but i want know the days of month
like i press 1 (means Jan ) then result will come the Jan month have 31 days. so plz do this i m waiting for your replay

by ass on Tuesday, August 31st 2010 at 07:16 PM

sdf


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia

Other Resources