Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
I have a text box where a user may enter any thing.

I need to check if the text entered contains a date like

if user is entering "I want this item by 11/21/2011"

or "10/15/2011" in both cases i want true else false.

Please suggest
Posted
Updated 16-Jul-17 11:34am

That is a lot harder than it looks - you have to presumably cope with any date format - I can think of three which could confuse you:
yyyy/MM/dd
dd/mm/yy
mm/dd/yy

If he enters "11/12/13" which is the year? Which is the month?
If he enters "11/12/2013" is that 11th Dec or 12th Nov?
What if he enters 1/2 - is that a half, or 1st Feb next year?
What if he enters Dec 12 2011?

If you can, try to change your UI so that dates are entered in a calendar control instead - it is a lot easier for you, and could be a lot clearer for the user too.
 
Share this answer
 
Comments
Orcun Iyigun 6-Dec-11 13:52pm    
5'ed!
raju melveetilpurayil 6-Dec-11 14:43pm    
5+
Monjurul Habib 8-Dec-11 15:34pm    
5!
You could first use for example String.Split[^] to break the text into pieces using whitespace as a separator and the for each item in the array use for example TryParse[^].

However as OriginalGriff wrote, you will have problems regarding to similar dates and months in different date formats sou you should somehow know the format the user uses, or to break the input to several controls as OriginalGriff suggested.
 
Share this answer
 
Comments
Monjurul Habib 8-Dec-11 15:34pm    
5!
Wendelius 12-Dec-11 16:05pm    
Thanks :)
I think Mika Wendelius has the idea to resolve such a scenario and below i will attempt to put it in code:
C#
Boolean hasDate = false;
DateTime dateTime = new DateTime();
String[] inputText = txtWords.Text().Split( " " );//split on a whitespace

foreach( String text in inputText )
{
   //Use the Parse() method
   try
   {
      dateTime = DateTime.Parse( text );
      hasDate = true;
      break;//no need to execute/loop further if you have your date
   }
   catch( Exception ex )
   {
      
   }
}

//after breaking from the foreach loop, you can check if hasDate=true
//if it is, then your user entered a date and you can retrieve it from the dateTime 

if( hasDate )
{
    //user entered a date, get it from dateTime
}
else
{
   //user didn't enter any date
}


By using DateTime.Parse(), you do not need to know the date format before hand, if the date format is not allowed, the DateTime.Parse() method will simply fail to parse the current "text", go into the catch, and the continue back into then foreach loop!

Hope that gives you a jump start,

Happy coding,
Morgs
 
Share this answer
 
v3
Comments
Morgs Morgan 7-Dec-11 12:23pm    
Thanks
Perić Željko 8-Dec-11 14:14pm    
What would happen if the user inputs the following message:
My birthday is06/11/2011.
Would program recognize date in that kind text message.
Monjurul Habib 8-Dec-11 15:34pm    
5!
Wendelius 12-Dec-11 16:06pm    
Exactly, something like that. My 5 :)
Hi,

if this is the only format of date and time then you can use,

C#
Regex stringDatePattern=new Regex("*[0-9][0-9][/][0-9][0-9][/][0-9][0-9[0-9][0-9]]*");
return stringDatePattern.IsMatch(TextBox.Text);


hope this will help you,

thanks
-amit.
 
Share this answer
 
Comments
AmitGajjar 7-Dec-11 1:39am    
Reason for 1 vote ?
Why not use a dedicated DateTimePicker Control and prevent errors by not allowing them to happen: like JQuery's: [^].
 
Share this answer
 
Comments
CHill60 16-Jul-17 18:58pm    
Doesn't fit the brief though. The, er, 6+ year old brief
BillWoodruff 17-Jul-17 0:22am    
Good grief ! I responded not to the current question, but to the thread that Ravi linked to from years ago in his response to the current question :)

Another example of my impaired vision.
try this
C#
string []format = new string []{"yyyy-MM-dd HH:mm:ss"};
string value = "2011-09-02 15:30:20";
DateTime datetime;

if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.NoCurrentDateDefault  , out datetime))
   Console.WriteLine("Valid  : " + datetime);
else
  Console.WriteLine("Invalid");
 
Share this answer
 
Comments
Abhi KA 6-Dec-11 9:01am    
is it working
_Zorro_ 6-Dec-11 9:10am    
What happens if the format is not yyyy-MM-dd HH:mm:ss ?
Member 14870442 11-Jul-20 13:07pm    
Thank you
public static bool IsDate(Object obj)
    {
        string strDate = obj.ToString();
        try
        {
            DateTime dt = DateTime.Parse(strDate);
            if (dt != DateTime.MinValue && dt != DateTime.MaxValue)
                return true;
            return false;
        }
        catch (Exception ex)
        {
            throw ex;
            return false;
        }
    }
 
Share this answer
 
v2
Comments
Abhi KA 6-Dec-11 9:01am    
correct
sonali_prajapati 6-Dec-11 9:02am    
but my string may have text also with the date strDate="items needed by 11/21/2011" i have to check if this text contains a date in the format of mm/dd/yyyy
RaviRanjanKr 6-Dec-11 9:19am    
A suggestion :- Always wrap your code in Pre tag.
Morgs Morgan 6-Dec-11 13:31pm    
How about putting this in your "catch": throw ex; return false; together? bad coding isn't!?
I would think throw ex; will stop program execution? take care next time..
C#
try
{
DateTime UserDate=Convert.ToDateTime("MM/dd/yyyy")
}
catch(Exception ex)
{
return "invalid date entered";
}


if(UserDate.Day==11 && UserDate.Day==12)
return true;
else
return false; 
 
Share this answer
 
Hello ,
this is my solution,
but it is related to regional settings in OS.

C#
/*
 * Created by Perić Željko
 * IDE SharpDevelop C#
 * Date: 6.12.2011
 * Time: 18:30
 * 
 * This is a small console application that partially solves the problem
 * because it recognizes only the date format in the text
 * that is set at the level of operating system , regional settings
 * in my case it is "Serbian cyrillic" and that means
 * DD.MM.YYYY or DD/MM/YYYY (day/month/year) if you want that program 
 * recognizes the other Date formats such as :
 * MM/DD/YYYY or other,
 * you have to write different kind of program
 * or you have to set regional settings for that Date format
 */
 
using System;
namespace DateCheck
{
	class Program
	{
		public static void Main(string[] args)
		{
			
			//
			// variable definition
			//
			
			string text = "";
			string date = "";
			int lenght = 0;
			int index = 0;
			bool da = false;
			DateTime D;
			
			//
			// write message for user to enter text
			// and read text from console
			//
			Console.WriteLine();
			Console.WriteLine("Hello,");
			Console.WriteLine("Enter text :");
			text = Console.ReadLine();
			
			//
			// wanted format of date is exactly DD/MM/YYYY or DD.MM.YYYY
			// it depends of local Date and Time format settings
			//
			index = 0;
			lenght = 0;
			lenght = text.Length - 9;
			while (index < lenght)
			{
				//
				// Since the format of date consists of 10 characters
				// we take first 10 characters and check if it is Date
				// if it is not we take next 10, starting from 2. character in the text
				// afther that next 10 starting from 3. character in the text ....
				// until we check all text.
				//
				date = text.Substring(index,10);
				try
				{
					D = DateTime.Parse(date);
					da = true;
					index = lenght;
				}
				catch
				{
					da = false;
					index = index + 1;
				}
			}
			
			//
			// If there is Date in the text write a message to user
			//
			if (da == true) 
			{
				Console.WriteLine();
				Console.WriteLine("In the text you have Date !");
			}
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
	}
}


In this case the Date don't need to be separated from text with space
example :
This is my message written08/12/2011and it was december.

in this example program recognize Date format in text.
 
Share this answer
 
v9
Comments
Perić Željko 8-Dec-11 13:59pm    
Sorry, but I do not know why sometimes the text editor want accept the </pre> tags so the code is not highlighted as in other solutions.
Perić Željko :( ?
Wendelius 8-Dec-11 14:34pm    
Pre tags fixed
Perić Željko 9-Dec-11 11:14am    
Thank you Mika.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900