I have a string. The string is like this
Hello I am a Coder, My DOB is 12/09/2011.
I want to extract the date from this sentence. How do I do this using C#? I do not want regular expressions. This was an interview question asked to me recently.
This is my try
string myStr = "Hello 12/3/2013";
DateTime s;
DateTime.TryParse(myStr,out s);
Console.WriteLine(s);
I am getting the output as
01-01-0001 00:00:00
Both C# and JavaScript support regular expressions. You can use this pattern to find that section of the string:
\d{2}/\d{2}/\d{4}
Of course that doesn't ensure that it's a valid date, e.g. 13/88/0000 would match that pattern. You'd then have to parse the string using something like Date.Parse.
However, since you've stated regular expressions are not an option, here's a very crude one-liner:
var input = "Hello I am a Coder, My DOB is 12/09/2011.";
DateTime date = new DateTime();
input.Split().SkipWhile(s => !DateTime.TryParse(s, out date)).Any();
Console.WriteLine(date); // 12/9/2011 12:00:00 AM
Since you don't want to use REGEX, simply split the string on space and then use DateTime.TryParseExact to see if any string gets parsed as DateTime
string str = "Hello I am a Coder, My DOB is 12/09/2011";
string[] array = str.Split();//splits on space
string dateFormat = "M/d/yyyy"; //works with both single digit and double digit
//(day/month) for parsing
//or d/M/yyyy depending your date culture
DateTime tempDateTime;
var result = array.FirstOrDefault(r =>
DateTime.TryParseExact
(r,
dateFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.NoCurrentDateDefault,
out tempDateTime));
Your result would contain the Date string, and your tempDateTime would contain the parsed DateTime.
Related
All of my friend.
I want to convert informal string to dateTime in c#. Here my string value is "01042016".How can convert? can i need another step to change DateTime.
This is my code:
string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate = Convert.ToDateTime(splitDate[0].ToString(),"dd/MM/yyyy"));
As we can see that the input date will be in the format ddMMyyyy so here the best option for converting the input to DateTime object is DateTime.TryParseExact the code for this will be :
string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate ;
if(DateTime.TryParseExact(splitDate[0],"ddMMyyyy",CultureInfo.InvariantCulture,DateTimeStyles.None,out startDate))
{
// Proceed with the startDate it will have the required date
}
else
// Show failure message
This will create an Enumerable where index 0 is the first date and index 1 is the second date.
string FinancialYear = "01042016-31032017";
var dateRange = FinancialYear.Split('-')
.Select(d => DateTime.ParseExact(d, "ddMMyyyy", CultureInfo.InvariantCulture);
If you are not sure of the format your best bet is using DateTime.Parse() or DateTime.TryParse()
You are not 100% guaranteed that the date will be parsed correctly, especially in cases where the day and month numbers could be in the wrong order.
It is best to specify a required date format if you can so you can be sure the date was parsed correctly.
if you string is in static format, you can convert it by reconvert it to valid string format first such as
string validstring = splitDate[0].ToString().Substring(4,4)+"-"+splitDate[0].ToString().Substring(2,2) +"-"+ splitDate[0].ToString().Substring(0,2);
DateTime startDate = Convert.ToDateTime(validstring,"dd/MM/yyyy"));
I am trying to format date entered by user.
Dates are provided in the following format:
d/M/yyyy (ie: 1/1/2012, but could be also 12/1/2012 or 1/12/2012)
however I need them converted to:
dd/MM/yyyy (ie: 01/01/2012)
I managed to do it in non-Regex way, like this:
string date = "1/1/2012";
if (date.IndexOf("/") == 1)
{
date = "0" + date;
}
if (date.Substring(4, 1) == "/")
{
date = date.Insert(3, "0");
}
I would really like to know how to do it with Regex.Replace, however, as it would probably be neater.
I tired different variations of the below:
string date = "1/1/2012"
date = Regex.Replace(date, #"\d{1}/", "0$&");
The above will work, but if the date is 12/1/2012, it will also make 102 out of 12. If I add ^ at the beginning of pattern I don't get the second number changed. I also tried combinations with [^|/] at the beginning, but also no luck. So at the moment it is either or.
Use word boundary \b which matches between a word character and a non-word character.
date = Regex.Replace(date, #"\b\d/", "0$&");
OR
date = Regex.Replace(date, #"\b(\d)/", "0$1/");
DEMO
If you're sure of the incoming format, I'd use DateTime.ParseExact instead, then use .ToString() to reformat the date:
DateTime dt = DateTime.ParseExact(input, "d/M/yyyy", CultureInfo.CurrentCulture);
string reformatted = dt.ToString("dd/MM/yyyy");
The string contains this value:
3/14/1952 12:00:00 AM
Now I want to show only in text box the date not the time how can I do this?
3/14/1952
I think most secure way is to parsing it to DateTime with DateTime.ParseExact method and using "d" standard date and time format .
As an example;
string s = "3/14/1952 12:00:00 AM";
DateTime dt = DateTime.ParseExact(s,
"M/dd/yyyy HH:mm:ss tt",
CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString("d"));
Output will be;
3/14/1952
Here a demonstration.
After parsing process, you can use this value in your TextBox with .Text property like;
TextBox1.Text = dt.ToString("d");
You can use string.Split that will give you array of strings and your required date string is at zero index.
string date = str.Split(' ')[0];
There are 2 solutions:
1. parse it to datetime and then convert it to your string format
var dateTime = DateTime.Parse("3/14/1952 12:00:00 AM");
var yourString = datetime.ToString("M/dd/yyyy");
2. just split it by string.Split method
string yourString = str.Split(' ')[0];
Try this:
Since you are using space for splitting, you don't have to specify the space character.
string MyString ="3/14/1952 12:00:00 AM";
string date=MyString.Split()[0];
OR
string date=MyString.Split().First();
I get a string from Excel as so: "\"11/01/2011 16:00\""
What's the most efficient way to trim this in C# so it can be parsed as a DateTime?
You could probably just trim the string, not sure how consistent that format will be though
var trimmedString = excelString.Trim('\\', '"');
That's assuming the string contains the slashes and those speech marks. If it's just the speech marks (because visual studio has escaped the string when displaying it) then all you need is
var trimmedString = excelString.Trim('"');
You don't need to trim it at all - you can just call DateTime.ParseExact or DateTime.TryParseExact which contains the quotes at each end:
string text = ...;
DateTime date = DateTime.ParseExact(text, "'\"'dd/MM/yyyy HH:mm'\"'",
CultureInfo.InvariantCulture);
I don't know whether that's more efficient than trimming (there's more parsing, but no extra string to create) but I would use it for its precision: if ever the data form changes (e.g. there's no longer a quote) you'll find out because you're stating your expectations, effectively.
string myString = "\"11/01/2011 16:00\"";
DateTime time = DateTime.Parse(myString.Substring(1, myString.Length - 2));
Always in that format? Can't you just substring the first 3 and last 3 characters and then Parse to a Date with a specific (supplied) date format?
s = s.Substring(1, s.Length-2);
You're looking for the parseExact method.
char[] trimChars = {'\"'};
string dateTime = "\"11/01/2011 16:00\"".Trim(trimChars);
DateTime result = DateTime.ParseExact(dateTime, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
I want to parse the date from the string where date formate can be any of different format.
Now to match date we can use DateTime.TryParseExact and we can define format as we needed and date will be matched for any different format.
string[] formats = {"MMM dd yyyy"};
DateTime dateValue;
string dateString = "May 26 2008";
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
MessageBox.Show(dateValue.ToString());
This matches with date.But this is not working for parse the date from the string that is it does not matched with the date which is in some string.
Like
if the date is "May 26 2008" then we can define format "MMM dd yyyy" and date will be matched.
But if date is in some string like "Abc May 26 2008" then date will not be matched.So for that can we use regular expression here ? If yes how ?
The string from I want to parse the date, is parsed from the html page and the string can be any different.
EDIT : I want to write the format like which matches any string in which there is a date using regex.
You could do a regular expression match on something like #"[A-Za-z]{3} \d{2} \d{4}" and feed whatever matches into DateTime.TryParseExact. It might break for alternate cultures however, I'm not sure if there are languages around that have month names only 2 letters short or something :)
Alternatively, you could extract the month names from cultureInfo.DateTimeFormat.AbbreviatedMonthNames and use that to build a slightly better targeted regular expression. It should also work for other cultures.
Edit - here's an example:
string text = "Apr 03 2010 foo May 27 2008 bar";
CultureInfo ci = new CultureInfo("en-US");
Regex regex = new Regex(#"(?<date>(" + String.Join("|",
ci.DateTimeFormat.AbbreviatedMonthNames, 0, 12) + #") \d{2} \d{4})");
// Builds this regex:
// (?<date>(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{2} \d{4})
var matches = regex.Matches(text);
foreach (Match match in matches)
{
string capturedText = match.Groups["date"].Value;
DateTime dt;
if (DateTime.TryParseExact(capturedText, "MMM dd yyyy", ci,
DateTimeStyles.None, out dt))
{
Console.WriteLine(capturedText + ": " + dt.ToLongDateString());
}
}
// Prints two parsed dates in long format
If it's English only and the format is "MMM dd yyyy" you can search where your string is [January|February|...|December] day year.
But you should first ask yourself why you're parsing any string. Can you not force the user to use a predefined format and validate that input?
You can customize the format according to your needs:
private const string DateTimeFormat = "dd-MMM-yy hh.mm.ss.ffffff tt";
public static bool TryParseToDateTime(this string stringValue, out DateTime result)
{
if (String.IsNullOrEmpty(stringValue))
{
result = DateTime.MinValue;
return false;
}
return DateTime.TryParseExact(stringValue, DateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
}
UPDATE:
You probably should use regular expressions to find strings that match date in text. You have to decide what date format you expect and write (or choose) an appropriate regular expression. For example, for "dd MMM yyyy" format you can use the following regular expressions:
^\d{2}\s{1}(Jan|Feb|Mar|Apr|May|Jun|Jul|Apr|Sep|Oct|Nov|Dec)\s{1}\d{4}$
by Stephen Lam from http://regexlib.com/REDetails.aspx?regexp_id=325
Alternatively you can browse this site to find appropriate expression.
If you know your date will start with a month then you can use substring to get that part. (Find occurence of Jan/Feb/ etc)
I think something like \w{3,8} \d\d \d\d\d\d[\s$] would work most of the time if it's in US format, but I wouldn't trust it too much if the text you're parsing could be just anything.
Here is the link to parse the date from the string which is very good.There is set of regex to parse the date from the string.
http://www.codeproject.com/KB/datetime/date_time_parser_cs.aspx