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 matters, we use dates continuously, so it is important to have the following concepts clear.
Index
1 - Creating the Datetime object
To create the Datetime object, we have many options to choose from:
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 ones, since they are the ones we use when we want to compare dates, and when we want to compare time in addition to 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 11 in the morning.
- 15 are the minutes.
- 16 are 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 developing Unix they needed a date to start counting from, and selected this one. There is no mystery or hidden reason behind it.
Finally, we can convert dates from a string, for which we have two options.
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 into a date.
Unfortunately, the example above will not work properly, only if we are in a machine from the United States, where the format for dates is month/day; if on the contrary, we are on a machine configured for Europe, the correct format for a date is day/month. *I don't know about South America.
1.1 - Localization with cultureinfo
To avoid this issue we have the CultureInfo type that is found within System.Globalization, which allows us to specify the format of a date, based on the country and language. The following code generates the CultureInfo type for Spanish (Spain).
CultureInfo cultureInfoES = new CultureInfo("es-SP");Meanwhile, if what we want is a South American country like Argentina, the code would be as follows:
CultureInfo cultureInfoAR = new CultureInfo("es-AR");Therefore, for the previous example (month/day) we need to use the United States CultureInfo:
CultureInfo cultureInfoUS = new CultureInfo("en-us");
DateTime ejemploFecha = Convert.ToDateTime("10/22/2015 12:10:15 PM", cultureInfoUS); Very important note: If we specify the CultureInfo incorrectly, the program will crash and execution will stop, so be sure of what you are doing.
1.2 - Properties of the Datetime type
Starting from the previous date, we can obtain most of the information we commonly use, such as day, month, day of the week, etc. All of this is available in the Datetime type, so we do not need to create any method to get it.
Here is a short list with some examples:
int dia = fecha.Day; //Returns the day of the month as a number (1, 2...30, 31)
int mes = fecha.month; //Returns the number of the month
int year = fecha.Year; //Returns the year
int hora = fecha.Hour; //Returns the hour
int minuto = fecha.Minute; //Returns the minute
int segundo = fecha.Second; //Returns the seconds.
string diaDeLaSemana = fecha.DayOfWeek; //Returns the day of the week as a string (Monday, Tuesday...Sunday)
int diaDelyear = fecha.DayOfYear; //Returns which day of the year it is as a number.
DateTime tiempo= fecha.Date; //returns hours:minutes:seconds
1.3 - Methods of the Datetime type
As in the previous case, the type itself comes with countless methods to be executed, such as adding days, months, or even time.
fecha.AddDays(1); //Adds one day to the current date
fecha.AddMonths(1);// Adds one month to the current date.
fecha.AddYears(1); //Adds one year to the current date.As we can see, all the examples are for adding, but what if we want to subtract days? For that, we still use the add method, but the value we pass will be negative.
fecha.AddDays(-1); //Subtracts one day from the current date
fecha.AddMonths(-1);// Subtracts one month from the current date.
fecha.AddYears(-1); //Subtracts one year from the current date.Lastly, 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, but now in the constructor we have 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 we can do so from days up to milliseconds, and we do it as follows:
DateTime fecha = new Datetime(2019, 01, 01); 
//fecha will have the value January 1, 2019 at 00h 00m
TimeSpan tiempo = new TimeSpan (1, 5, 30, 5); 
//we create a timespan object with a value of 1 day, 5 hours, 30 minutes, 5 seconds
DateTime fechaActualizada = fecha.Add(tiempo);
//We add the time to the previous date
//Result: January 2, 2019 at 5:30 AM.
2 - Date comparison
Comparing dates is very important in the real world and is something that must be very clear. For example, we compare dates in filters or database queries, or LINQ queries like the one we saw in the previous post.
When comparing, we can do it in two ways:
- Use the DateTime.Compare(fecha1, fecha2)method within the staticDateTimetype.
- Use the first date itself to compare against the second, fecha1.CompareTo(fecha2);
In both cases the result returned is the same; it will return an integer (int) corresponding to the following:
- less than 0if the first date is earlier than the second.
- 0if both dates are equal.
- greater than 0if 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 indistinctly
int fechaResultado = fecha1.CompareTo(fecha2); 
if (fechaResultado < 0)
{
	Console.WriteLine("La primera fecha es menor");
}
else if (fechaResultado == 0)
{
	Console.WriteLine("Las fechas son iguales");
}
else
{
	Console.WriteLine("La segunda fecha es menor");
}
3 - Printing the date with format
Finally, we arrive at 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 pay attention to whether we need to use CultureInfo.
By default, DateTime gives us several functions to print dates in default formats, which are the following:
DateTime fecha= new DateTime(1989, 11, 2, 11, 15, 16);
fecha.ToString(); // result: 02/11/1989 11:15:16
fecha.ToShortDateString(); //result: 02/11/1989
fecha.ToLongDateSTring(); //Result: Thursday 2 October 1989
fecha.ToShortTimeString(); //result: 11:15In addition to the default options, we can create our own version using the .ToString() method, since if we pass it a parameter, the compiler translates it into what we need.
The previous examples can be represented only with .ToString() as follows:
But what is the use of being able to print something that we already can print before? The .ToString() method is much more powerful, since we can pass it a combination of characters so that it displays the format just as we need. For example, yyyy is translated as year, MM is translated as month.
Something very common in all applications is to have a log. Logs save 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 . also appear in the result.
Apart from these, there are many more codes to pass in the .ToString() method. Later you can use any of the available methods in the string class.
Finally, a table with everything the .ToString() method allows you to add. Notice the difference between uppercase and lowercase.
| Specifier | 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 | Sortable date and time | 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 2 digits | 11 | 
| HH | Hour with 2 digits in 24h format | 23 | 
| mm | Minute with 2 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 2 digits | 89 | 
| yyyy | Year with 4 digits | 1989 | 
If there is any problem you can add a comment bellow or contact me in the website's contact form
 
                    