In this tutorial, we will see how to work with the Datetime
type, which allows us to handle dates. In the professional world, which is basically what's important, we use dates constantly, so it's important to have the following concepts clear.
Index
1 - Creating the Datetime Object
To create a Datetime object, we have a multitude of options as shown:
public DateTime(long ticks);public DateTime(long ticks, DateTimeKind kind);public DateTime(int year, int month, int day);public DateTime(int year, int month, int day, Calendar calendar);public DateTime(int year, int month, int day, int hour, int minute, int second);public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind);public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar);public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond);public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind);public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar);public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind);
However, two of them are the most common, as these are the ones we use when comparing dates, or when comparing time as well as dates.
public DateTime(int year, int month, int day);public DateTime(int year, int month, int day, int hour, int minute, int second);
So to create a date object we will use the following statement:
DateTime testFecha = new DateTime(1989, 11, 2, 11, 15, 16);
Where:
- 1989 is the year.
- 11 is the month.
- 2 is the day.
- 11 is the hour, in 24h format, so it's 11 AM.
- 15 is the minutes.
- 16 is the seconds.
Another option to create dates is to use "ticks," which count from January 1, 1970.
public DateTime(long ticks);
Why did they choose January 1, 1970? Well, the reason is that when they were developing unix, they needed a date to start counting from, and they selected that one. There's no secret or hidden purpose.
Finally, we can convert dates from a string in two ways.
DateTime ejemploFecha = Convert.ToDateTime("10/22/2015 12:10:15 PM"); DateTime ejemploFecha = DateTime.Parse("10/22/2015 12:10:15 PM");
Both options are completely valid, although they have slight internal differences; both will convert the text to a date.
Unfortunately, the example above doesn't work correctly, except if we're on a US machine, where the date format is month/day; if instead we're on a machine configured for Europe, the correct format for a date is day/month. (*I do not know about South America.)
1.1 - Localization with cultureinfo
To avoid this problem, we have the CultureInfo
type found within System.Globalization
that allows us to specify the date format based on country and language. The following code creates a CultureInfo
for Spanish in Spain.
CultureInfo cultureInfoES = new CultureInfo("es-SP");
If what we want is a South American country, such as Argentina, we would use the following code:
CultureInfo cultureInfoAR = new CultureInfo("es-AR");
So, for the previous example (month/day) we have to use the US CultureInfo
:
CultureInfo cultureInfoUS = new CultureInfo("en-us");DateTime ejemploFecha = Convert.ToDateTime("10/22/2015 12:10:15 PM", cultureInfoUS);
Very important note: If we indicate the wrong CultureInfo
, the program will crash and stop executing so we have to be sure of what we're doing.
1.2 - Datetime Type Properties
From the previous date, we can get the majority of information we commonly use, such as day, month, weekday, etc. All of this comes as part of the Datetime Type, so we don't have to create any methods to obtain them.
Here I show a short list with some examples:
int dia = fecha.Day; //Gives us the day of the month as a number (1, 2...30, 31)int mes = fecha.month; //Gives us the month numberint year = fecha.Year; //Gives us the yearint hora = fecha.Hour; //Returns the hourint minuto = fecha.Minute; //Returns the minuteint segundo = fecha.Second; //Returns the seconds.string diaDeLaSemana = fecha.DayOfWeek; //Returns the day of the week as a word (Monday, Tuesday... Sunday)int diaDelyear = fecha.DayOfYear; //Returns the day number of the year.DateTime tiempo= fecha.Date; //Returns hours:minutes:seconds
1.3 - Datetime Type Methods
As in the previous case, the type itself brings countless methods to be executed, among which we can add days, months, or even time.
fecha.AddDays(1); //Will add one day to the current datefecha.AddMonths(1);// Will add one month to the current date.fecha.AddYears(1); //Will add one year to the current date.
As we can see, all the examples are for adding, but what happens if we want to subtract days? To do this, we must also use the add method, except the value we pass will be negative.
fecha.AddDays(-1); //Will subtract one day from the current datefecha.AddMonths(-1);// Will subtract one month from the current date.fecha.AddYears(-1); //Will subtract one year from the current date.
Finally, if what we want is to add time, we have to use a specific type.
1.4 - The TimeSpan Type
Similar to the previous case, except now the constructor gives us time options
public TimeSpan(long ticks);public TimeSpan(int hours, int minutes, int seconds);public TimeSpan(int days, int hours, int minutes, int seconds);public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds);
As we can see, to create the TimeSpan
time we can do so from days up to milliseconds. We will do it as follows:
DateTime fecha = new Datetime(2019, 01, 01); //fecha will have the value January 1, 2019, at 00h 00mTimeSpan tiempo = new TimeSpan (1, 5, 30, 5); //We create a timespan object with a value of 1 day, 5 hours, 30 minutes, 5 secondsDateTime fechaActualizada = fecha.Add(tiempo);//We add the time to the previous date//Result: January 2, 2019, at 5:30 AM.
2 - Comparing Dates
Comparing dates is very important in the real world and is something that must be very clear. For example, we compare dates inside filters or in database queries, or LINQ queries like the one we saw in the previous post.
When comparing, we can do so in two ways:
- Use the
DateTime.Compare(fecha1, fecha2)
method within the staticDateTime
type. - Use the date itself to compare it to the second: fecha1.CompareTo(fecha2);
In both cases the result is the same: it will return an integer (int) corresponding to the following:
less than 0
if the first date is earlier than the second.0
if both dates are equal.greater than 0
if the first date is later than the second.
DateTime fecha1 = new DateTime(1989, 11, 2);DateTime fecha2 = new DateTime(1978, 4, 15);int fechaResultado = DateTime.Compare(fecha1, fecha2);//Or either wayint fechaResultado = fecha1.CompareTo(fecha2); if (fechaResultado < 0){ Console.WriteLine("The first date is earlier");}else if (fechaResultado == 0){ Console.WriteLine("The dates are equal");}else{ Console.WriteLine("The second date is earlier");}
3 - Printing the Date with Format
Finally, we reach the crucial part since when working a lot with dates, we also want to be able to print them. And in this scenario, as in the previous one, we must also check if we need to use CultureInfo
.
By default, DateTime
provides several functions to print dates with default formats. These are:
DateTime fecha= new DateTime(1989, 11, 2, 11, 15, 16);fecha.ToString(); // result: 02/11/1989 11:15:16fecha.ToShortDateString(); //result: 02/11/1989fecha.ToLongDateSTring(); //Result: Thursday 2 October 1989fecha.ToShortTimeString(); //result: 11:15
Besides the default options, we can create our own version using the .ToString()
method, as if we pass a value as a parameter, the compiler translates it to what we need.
The previous examples can be represented using only .ToString()
as follows:
But of what use is it to print something we could already print before. The .ToString() method is much more powerful, since we can pass a combination of characters to show the format exactly as needed. For example, yyyy
translates to the year, MM
is the month.
Something very common in all applications is to have a log, and logs store date and time with microsecond precision. We can create a message from a date with a format similar to a log.
DateTime fecha= new DateTime(1989, 11, 2, 11, 15, 16, 123);fecha.ToString(yyy-MM-ddThh:mm:ss.ms); // result: 1989-01-11T11:15:16.123
As we can see, characters like -
or .
are also represented in the result.
Besides these, there are many more codes to pass in the .ToString()
method, and we can later use any methods available in the string class.
Finally, a table with everything the .ToString()
method allows to add. Note the difference between uppercase and lowercase.
Specification | Description | Output |
d | Short date | 02/11/1989 |
D | Long date | Thursday 2 November 1989 |
t | Short time | 11:15 |
T | Long time | 11:16:16 |
f | Full date and short time | Thursday 2 November 1989 11:15 |
F | Full date and long time | Thursday 2 November 1989 11:15:16 |
g/G | Default date and time | 02/11/1989 11:15 |
M | Day and month | 02-Nov |
r | RFC 1123 date | Thu 02 Nov 1989 11:15:16 GTM |
s | Date and time for sorting | 1989-11-02T11:15:16 |
u | Universal time, with timezone | 1989-11-02T11:15:16z |
Y | Month year | November 1989 |
dd | Day | 2 |
ddd | Short day | Thu |
dddd | Full day | Thursday |
hh | Hour with two digits | 11 |
HH | Hour with two digits 24h format | 23 |
mm | Minute with two digits | 15 |
MM | Month | 11 |
MMM | Short month name | Nov |
MMMM | Long month name | November |
ss | Seconds | 16 |
fff | Milliseconds | 123 |
tt | AM/PM | PM |
yy | Year with two digits | 89 |
yyyy | Year with four digits | 1989 |
If there is any problem you can add a comment bellow or contact me in the website's contact form