Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Don't reinvent wheels, use the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx" rel="nofollow"><code>DateTime.TryParseExact</code></a> method which is built specifically for this purpose. Forget about regexes and substrings when you are dealing with dates in the .NET framework:</p> <pre><code>public static bool CheckDate(string number, out DateTime date) { return DateTime.TryParseExact(number, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date); } </code></pre> <p>And now as you can see defining the <code>CheckDate</code> becomes kinda meaningless because it already exists in the BCL. You would simply use it like this:</p> <pre><code>string number = "that's your number coming from somewhere which should be a date"; DateTime date; if (DateTime.TryParseExact( number, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date )) { // the number was in the correct format // =&gt; you could use the days, months, from the date variable which is now a DateTime string dd = date.Day.ToString(); string mm = date.Month.ToString(); string yyyy = date.Year.ToString(); // do whatever you intended to do with those 3 variables before } else { // tell the user to enter a correct date in the format dd/MM/yyyy } </code></pre> <hr> <p>UPDATE: </p> <p>Since I got a remark in the comments section that I am not actually answering the question, you could use a similar approach to the one I recommend. But please, promise me you will <strong>never write a code like this</strong>, it's just for illustration of the TryXXX pattern.</p> <p>define a model:</p> <pre><code>public class Patterns { public string DD { get; set; } public string MM { get; set; } public string YYYY { get; set; } } </code></pre> <p>and then modify your CheckDate method so that it sends an out parameter:</p> <pre><code>public static bool CheckDate(string number, out Patterns patterns) { patterns = null; string new_number = number.ToString(); if (new_number.Length == 8) { Patterns = new Patterns { YYYY = new_number.Substring(0, 4), MM = new_number.Substring(4, 2), DD = new_number.Substring(6, 2) } return true; } else { return false; } } </code></pre> <p>which you could use like this:</p> <pre><code>string number = "that's your number coming from somewhere which should be a date"; Patterns patterns; if (CheckDate(numbers, out patterns) { string dd = patterns.DD; string mm = patterns.MM; string yyyy = patterns.YYYY; // do whatever you intended to do with those 3 variables before } else { // tell the user to enter a correct date in the format dd/MM/yyyy } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload