Click here to Skip to main content
15,917,059 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hello i have a string i my application which is i am retrieving from database i want to only select the date from my string

What I have tried:

my string is string var = P 2016-10-31; i have tried this but i can able get only P from this what can i do so i can able to select only date (2016-10-31)
Posted
Updated 31-Oct-16 2:26am
Comments
Perić Željko 31-Oct-16 9:36am    
On this link there is interesting stuff about strings and dates inside them :

http://www.codeproject.com/Answers/297126/Csharp-How-to-check-if-a-string-contains-a-date#answer8

C#
string myString = "P 2016-10-31";
string[] parts = mystring.Split(' ');
DateTime date = DateTime.ParseExact(parts[1], "yyyy-MM-dd", CultureInfo.InvariantCulture);
 
Share this answer
 
It really depends on the format of the data - if it's always a single char, a space, and then the date, it's trivial:
C#
string input = "P 2016-10-31";
string justTheDate = input.Substring(2);
DateTime dt;
if (DateTime.TryParseExact(justTheDate, "yyyy-M-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
    {
    ...
    }

If it varies, then you need to look closely at exactly what it can be and maybe consider a Regex instead.
 
Share this answer
 
C#
string s = "P 2016-10-31";
DateTime dt;
DateTime.TryParseExact(s, "P yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dt);
 
Share this answer
 
I had a similar problem a while back, where multiple dates, with multiple structures, could be anywhere in a document. The following code got them all:
(Note: I'm in Australia, so short date format is dd/MM/yy).
C#
string test;
 
Regex re = new Regex(@"\b(?<datetime>" +
		// Date part
		@"((" +
			@"(\d{1,2}[\/\-\.]\d{1,2}[\/\-\.]\d{2}(\d{2})?)" +
			@"|(\d{1,2}\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-zA-Z]*,?\s+\d{2}\d{2}?)" + 
			@"|((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-zA-Z]*\s+\d{1,2},?\s+\d{2}\d{2}?)" +
			@"|(\d{4}\-\d{1,2}-\d{1,2})" +
		@")" +
		// Optional time part
		@"(" +
			@"[T\s]?\d{1,2}:\d{1,2}(:\d{1,2}(\.\d+)?)?(([AP]M)|([\+\-][12]?\d:\d{1,2})|Z)?" +
		@")?)" +
		// Stand alone time
		@"|(\d{1,2}:\d{1,2}(:\d{1,2}(\.\d+)?)?(([AP]M)|([\+\-][12]?\d:\d{1,2})|Z)?)" +
    @")\b", RegexOptions.IgnoreCase);
 
test = " 29/11/15 xxx 29 November 2015 6:27PM xxx 2015-11-29T18:27:45.50+10:00 xxx 2015-11-29 18:27:45.50Z xxx NOV 29, 2015 xxxx 21:15";
 
MatchCollection matches = re.Matches(test);
 
foreach (Match m in matches) {
	DateTime dt;
	if (DateTime.TryParse(m.Groups["datetime"].Value, out dt)
		Console.WriteLine("{0}\t\t{1}", m.Groups["datetime"].Value, dt);
}
 
Share this answer
 
v2

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