C# DateTime parse
C# DateTime parse tutorial shows how to convert strings into DateTime objects in C#.
Advertisements C# DateTime
The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar.
Parse methods
The DateTime.Parse converts the datetime string into a DateTime . It automatically tries to figure out the datetime format.
The DateTime.ParseExact method converts the specified string representation of a datetime to a DateTime . The datetime string format must match the specified format exactly; otherwise an exception is thrown.
Date & time is culture specific; the methods either use the current culture or accept a specific culture.
Advertisements C# DateTime.Parse
We use DateTime.Parse to converts datetime strings into DateTime .
We have a bunch of datetime strings in an array. We convert them into DateTime objects with DateTime.Parse .
C# DateTime.ParseExact
With DateTime.ParseExact , we explicitly specify the format of the datetime string.
The second parameter of the DateTime.ParseExact is the format of the datetime string. The third parameter is the culture.
Advertisements C# DateTime FormatException
If the DateTime.Parse method fails, it throws a FormatException .
In the example, we handle a FormatException .
C# DateTime.TryParse
The DateTime.TryParse method converts the specified datetime string into DateTime . It returns a boolean value that indicates whether the conversion succeeded. It parses the string into its parameter.
In the example, we try to parse a datetime string. If the methods succeeds, we print the parsed object; otherwise, we print an error message that it failed.
Advertisements C# DateTime.Parse with CultureInfo
Dates and times are culture specific. We need to pass the culture information to the parsing methods in case of non-default culture used.
In the example, we parse three dates written in Slovak culture. The culture is passed as the second parameter of the DateTime.Parse method.
C# parse Last-Modified header value
The Last-Modified response HTTP header contains a datetime when the origin server believes the resource was last modified.
In the example, we parse the Last-Modified header value of an HTTP response.
Не зависимый от локали парсинг даты из строки в DateTime
В одном из проектов, волею судеб у меня приключилось что дата приходит из сторонней системы в виде строки формата Y-m-d и эту дату нужно сложить в столбец типа date в MS SQL сервере. В самой программе осуществляется запрос INSERT с этими данными. И одна ленивая задница (конечно это был я) решила не преобразовывать данные внутри программы, а просто сунуть их в параметр запроса. И вот что из этого получилось.
А получилось как всегда приключения в продуктиве. Через несколько лет эксплуатации программы появился клиент у которого настройки MS SQL подразумевали форматирование даты в виде Y-d-m, то есть день месяца теперь в середине строки, а не в конце. Маковкой на тортике было условие, что нельзя изменять настройки у сервера. То есть жить с тем, что дадено.
Возможные варианты конвертирования даты в MS SQL
После консультации с гуру MS SQL мне были предложены варианты решения проблемы:
- При начале сессии изменять формат строки даты по-умолчанию с помощью команды SET DATEFORMAT https://docs.microsoft.com/ru-ru/sql/t-sql/statements/set-dateformat-transact-sql?view=sql-server-ver15. Вариант подкупает своей простотой. Но уж очень он похож на костыль.
- Изменить саму строку для передачи в запрос. Вариант упоротый, конечно. Получить значение текущего формата даты MS SQL сервера можно с помощью запроса select date_format from sys . dm_exec_sessions where session_id = @ @ spid . Делать так мы, конечно, не будем.
- Прицеплять к параметру запроса нормальный тип DateTime и пусть драйвер ODBC MS SQL делает свою работу какой бы ни был в последствии формат даты. Вот это вариант хорош и закрывает технический долг который я сам себе сделал.
Выбор места в коде для конвертирования
Для задания параметров запроса в проекте я использую метод AddWithValue
В переменной serv у нас data class в котором находятся параметры из другой части программы и где мы получаем в поле Birthday нашу строку с датой.
Возникает логичный вопрос: а где правильно будет поменять этот параметр? В data class или в момент подготовки запроса?
Самый-самый правильный вариант: конечно, в data class. То есть мы должны в момент получения данных преобразовать строку в тип DateTime и уже внутри программы манипулировать ей.
Другой вариант. Взвешивания «за» и «против». Юнит тестами не получится протестировать все кейсы взаимодействия с data class-ом, нужно поднимать среду интеграционного тестировать и UAC + подключать тестировщиков. Что выйдет в очень дорого и долго. Если изменить только перед конкретным применением в запросе, то можно будет быстро исправить кейс и утилита будет приносить счастье пользователям.
Да, в общем, я выбрал второй вариант ибо бюджеты, сроки, и всё такое. Ну и в который раз убедился, что срезав углы при разработке, получаем эти углы в виде кочек при эксплуатации.
Конвертирование строки в DateTime в C#
Отбросив лирику, приступим к реализации. Нам дан формат строки Y-m-d и нам нужно его вставить в столбец DateTime в MS SQL.
Сходу могу предложить два варианта:
- Использовать метод класса Convert.ToDateTime
- Использовать метод класса DateTime.Parse
Для начала, проведём исследование через юнит-тестирование как эти методы помогут нам в решении задачи. Все исходные коды собраны в проект и расположены на GitHub https://github.com/a13xg0/str_to_date_csharp.
Тест для проверки нашего условия довольно прост и включает в себя дату, выходящую за пределы количества месяцев:
Converting a String to DateTime
How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime ?
17 Answers 17
Since you are handling 24-hour based time and you have a comma separating the seconds fraction, I recommend that you specify a custom format:
You have basically two options for this. DateTime.Parse() and DateTime.ParseExact() .
The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.
ParseExact will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. This way, you can easily detect any deviations from the expected data.
You can parse user input like this:
If you have a specific format for the string, you should use the other method:
«d» stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.
String to DateTime in C# and VB.Net
In .Net, you can work with date and time easy with the DateTime class. You can use the methods like Convert.ToDateTime(String), DateTime.Parse() and DateTime.ParseExact() methods for converting a string-based date to a System.DateTime object.
Convert.ToDateTime(String)
This method will converts the specified string representation of a date and time to an equivalent date and time value
VB.Net
DateTime.Parse()
DateTime.Parse method supports many formats. It is very forgiving in terms of syntax and will parse dates in many different formats. That means, this method can parse only strings consisting exactly of a date/time presentation, it cannot look for date/time among text.
VB.Net
DateTime.ParseExact()
ParseExact method will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. The format of the string representation must match the specified format exactly.
VB.Net
The null(Nothing) parameter is the CultureInfo object that corresponds to the current culture is used.
CultureInfo
When numbers, dates and times are formatted into strings or parsed from strings then a culture (CultureInfo)is used to determine how it is done. If you know what specific culture that your dates and decimal or currency values will be in ahead of time, you can use that specific CultureInfo property, e.g. CultureInfo(«en-US»).
The CultureInfo.InvariantCulture property is neither a neutral nor a specific culture. It is a third type of culture that is culture-insensitive. It is associated with the English language but not with a country or region.
VB.Net
DateTime.TryParse method
DateTime.TryParse converts the specified string representation of a date and time to its DateTime equivalent using the specified culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.
This method is similar to the DateTime.Parse(String) method, except that the TryParse(String, DateTime) method does not throw an exception if the conversion fails. Also, this method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. The TryParse method is culture dependent so be very careful if you decide use it.
Looking for a .Net job ?
There are lot of opportunities from many reputed companies in the world. Chances are you will need to prove that you know how to work with .Net Programming Language. These .Net Interview Questions have been designed especially to get you acquainted with the nature of questions you may encounter during your interview for the subject of .Net Programming. Here’s a comprehensive list of .Net Interview Questions, along with some of the best answers. These sample questions are framed by our experts team who trains for .Net training to give you an idea of type of questions which may be asked in interview.
How to to set datetime object to null ?
By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. More about. Datetime object to null
How to find date difference ?
A calculation using a DateTime structure, such as Add or Subtract, does not modify the value of the structure. Instead, the calculation returns a new DateTime structure whose value is the result of the calculation. The DateTime.Substract method may be used in order to find the date-time difference between two instances of the DateTime method. More about. Find date difference
DateTimePicker Control
The DateTimePicker control has two parts, a label that displays the selected date and a popup calendar that allows users to select a new date. The most important property of the DateTimePicker is the Value property, which holds the selected date and time. More about. DateTimePicker