I get data from a service call and want to make sure the string is in the correct date format, for example:
2015-Nov-19
I tried using the parsing function with the format yyyy-mmm-dd, but also gives dates like 2015-11-19. What should I do?
yyyy-mmm-dd
2015-11-19
Use DateTime.TryParseExact
DateTime dt; string[] formats = { "yyyy-MMM-dd"}; if (!DateTime.TryParseExact(dateValue, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { //your condition fail code goes here return false; } else { //success code }
You need to use a MMMspecifier instead of MMMwith English culture, for example InvariantCulture. None MMMas a custom date and time specifier.
MMM
InvariantCulture
, DateTime.TryParseExact , string[] , .
DateTime.TryParseExact
string[]
string s = "2015-Nov-19"; // or 2015-11-19 DateTime dt; string[] formats = {"yyyy-MMM-dd", "yyyy-MM-dd"}; if(DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { // Successfully parse }
MM , , M.
MM
M
DateTime.TryParseExact .
. , , . , .
:
DateTime dt = DateTime.Now; Console.WriteLine(dt.ToString("yyyy-MMM-dd HH:SS"));
. , , DateTime. DateTime.
string stringdate = "2015-Nov-19"; DateTime date = Convert.ToDateTime(stringdate); string tempdate = date.ToString("yyyy-MMM-dd"); if (tempdate == stringdate) { // Successfully parsed string goes here }
, , . 2015-11-19, .
Source: https://habr.com/ru/post/1616574/More articles:Refpount Delphi 7 error when copying a record to dynamically allocated memory - automatic-ref-countingProviding a callback for async script - javascriptHow to create a JSONObject? Android - javaEmulate pthread_kill with C ++ threads - c ++Vigenere Square Lookup (using string arrays) - c #Nodejs close variable not updated in module - javascriptКак получить информацию о заметках из сообщений с помощью python/tumblr api? - pythonBest way to find how many times a string (or substring) occurs in a large string C # - stringFunctional Button Buttons - applescriptDoes the Java regular expression library optimize for any characters. *? - javaAll Articles