In this tutorial we are going to work with dates and times. Additionally, some of the methods from the DateTime object will be explained.
First of all, create a new console application project.
Let's start by creating a new variable of the data type DateTime which stores a date and time.
The value is for this example the current date and time. We can call it by using the variable "Now" in the DateTime object.
The next step would be to print the date and time into the console.
The "ToString()" method can convert our DateTime object into a string by using our location.
This means that e.g. a person from the USA would get a 12-hour based time-string and a person from Europe would get a 24-hour based time-string.
The ToString() method returns a string with the date and the time.
If only the date or time is wanted, we can use the implemented methods from the DateTime object.
Write following code into your project to see the results of the methods by running your application:
To add days, months, hours, ... the DateTime object has methods called AddDays, ....
If you want to subtract days or something like that, then you have to add a negative value because the DateTime object hasn't a method for subtracting.
As you can see in the code above that a method was called after a method.
This works because the result of the first method is a DateTime object and from this object we can call every method.
Back to the code:
Till now we can print the date and time into the console but not only e.g. the month.
To get only a single one we can call the Month, Year, ... variables.
Before we created a DateTime object from the current date and time. Now let's create it by using our input.
Creating a new DateTime object with a specific date and time is made by calling the constructor of the DateTime object with the parameters for the year, month and day.
An alternative would be to create a new DateTime object from a string.
Please keep in mind that the string looks different in each country.
For example, the month and day of the year change position in Europe in comparison to the USA.
By subtracting two DateTime values the result will be a period of time.
This TimeSpan object has useful methods like the total amount of days in this period of time.
Complete program code:
static void Main(string args)
DateTime myValue = DateTime.Now;
DateTime myBirthday = new DateTime(1969, 12, 7);
DateTime myBirthday2 = DateTime.Parse("12/7/1969");
TimeSpan myAge = DateTime.Now.Subtract(myBirthday2);