C# - Extract Date from String using StreamReader - c#

How would I go about getting just the date from the following string?
"DateOfTest_01-30-2018-1_003"
This string is in position 8 in a CSV file, which I am looping through and parsing. What I have is:
while (!reader.EndOfStream) {
var splitLine = reader.ReadLine().SplitCommaSeparatedValues();
sample.RunDate = splitLine[8];
WriteLog("Run Date = " + sample.RunDate);}
So I need to extract characters from the string that fall between "_" and "-1" and convert the result to /mm/dd/yyyy format.
Thanks in advance for any assistance!

Better will be regular expression in this case: "(DateOfTest_)(\d{2}-\d{2}-\d{4})(-\d_\d{3})". Second group will be date. In c# you can use Regex.Match. MSDN

Use DateTime.ParseExact:
var culture = System.Globalization.CultureInfo.InvariantCulture;
var strToParse = splitLine[8].Substring(11, 10);
var date = DateTime.ParseExact(strToParse, "MM-dd-yyyy", culture);
var formattedStr = date.ToString("MM/dd/yyyy", culture);

You could use Regex matching to determine date string in the input.
var pattern = #"(?<=_)(.*?)(?=-1)";
var input = "DateOfTest_01-30-2018-1_003";
if (Regex.IsMatch(input, pattern))
{
var dateStr = Regex.Match(input, pattern);
var date = DateTime.ParseExact(dateStr.Value, "MM-dd-yyyy",null);
}

Unless you absolutely need the data at just that exact moment move your date parser outside of your reader.
After that, the answer really relies on whether or not the string in that field is always formatted the same way.
As others have pointed out, if the string is always of the same format you can substring the date out of the string. Then you can either do use one of the several built-in date format methods, or since it is formatted correctly, do a string.Replace("-", "//")
If the string format changes you'll need to try some regex to help you identify the substring to pull out.
My biggest point is that I think you should do this formatting of your field outside of your reader.

string TestString = "DateOfTest_01-30-2018-1_003";
Regex TestRegex = new Regex(#"(DateOfTest_)(\d{2}-\d{2}-20\d{2})(-\d_\d{3})");
string ExactDateFormat = "MM-dd-yyyy";
if (TestRegex.IsMatch(TestString))
{
Date = TestRegex.Match(TestString).Groups[2].ToString();
Date = DateTime.ParseExact(Date, ExactDateFormat, null).ToShortDateString();
}

Related

How to Extract datetime value with AM/PM && remember its position from string

I've see
this post. What if my string is string x = "Tomorrow 04-26-19 09:14AM sunrise.";, basically the datetime value is always in mm-dd-yy hh:mm<AM/PM> format. So I'd need to extract this value of 04-26-19 09:14AM and remember the starting position which = 9.
This works nicely for me:
string x = "Tomorrow 04-26-19 09:14AM sunrise.";
var regex = new Regex(#"\d{2}-\d{2}-\d{2} \d{2}:\d{2}(AM|PM)");
var match = regex.Match(x);
if (match.Success)
{
var prefix = x.Substring(0, match.Index);
var value = DateTime.ParseExact(match.Value, "MM-dd-yy hh:mmtt", System.Globalization.CultureInfo.CurrentCulture);
var suffix = x.Substring(match.Index + match.Length);
}
It's using Regex to find a potential DateTime string and then determines the prefix part of the string, the DateTime value, and the suffix part of the string.
It gives me:
"Tomorrow "
2019/04/26 09:14:00
" sunrise."
If "tomorrow" and "sunshine" aren't necessarily always going to be present in a string like x but the format of this string will be similar, I'd probably split these strings according to the space character like this.
x.Split(' ')
with indices
string strDate = x.Split(' ')[1];
string strTime = x.Split(' ')[2];
& then join those sets of strings
string dt = $"{strDate} {strTime}";
& then probably use the DateTime.ParseExact functionality to craft an actual DateTime object out of what I parsed.
DateTime.ParseExact(dt, "MM-dd-yy hh:mmtt", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal)
I generally use assumelocal so that I know the time won't be UTC.
"tt" is a placeholder for AM or PM.
If this is something you'll have to do iteratively, then I would probably create a method for this, and then simply call it routinely.

How to remove DateTime substring from string

I have a bunch of strings, some of which have one of the following formats:
"TestA (3/12/10)"
"TestB (10/12/10)"
The DateTime portion of the strings will always be in mm/dd/yy format.
What I want to do is remove the whole DateTime part including the parenthesis. If it was always the same length I would just get the index of / and subtract that by the number of characters up to and including the (. But since the mm portion of the string could be one or two characters, I can't do that.
So is there a way to do a .Contains or something to see if the string contains the specified DateTime format?
You could use a Regular Expression to strip out the possible date portions if you can be sure they would consistently be in a certain format using the Regex.Replace() method :
var updatedDate = Regex.Replace(yourDate,#"\(\d{1,2}\/\d{1,2}\/\d{1,2}\)","");
You can see a working example of it here, which yields the following output :
TestA (3/12/10) > TestA
TestB (10/12/10) > TestB
TestD (4/5/15) > TestC
TestD (4/6/15) > TestD
You could always use a regular expression to replace the strings
Here is an example
var regEx = new Regex(#"\(\d{1,2}\/\d{1,2}\/\d{1,2}\)");
var text = regEx.Replace("TestA (3/12/10)", "");
Use a RegEx for this. I recommend:
\(\d{1,2}\/\d{1,2}\/\d{1,2}\)
See RegExr for it working.
Regex could be used for this, something such as:
string replace = "TestA (3/12/10) as well as TestB (10/12/10)";
string replaced = Regex.Replace(replace, "\\(\\d+/\\d+/\\d+\\)", "");
If I'm understanding this correctly you want to just acquire the test name of each string. Copy this code to a button click event.
string Old_Date = "Test SomeName(3/12/10)";
string No_Date = "";
int Date_Pos = 0;
Date_Pos = Old_Date.IndexOf("(");
No_Date = Old_Date.Remove(Date_Pos).Trim();
MessageBox.Show(No_Date, "Your Updated String", MessageBoxButton.OK);
To sum it up in one line of code
No_Date = Old_Date.Remove(Old_Date.IndexOf("(")).Trim();

Can I use Format instead of using substring?

Using a memory profile on my C# desktop app I have found that strings are not being released from memory causing a slow and gradual buildup.
I have this code:
var ToYYYMMDDHHMMSS = "YYYMMDDHHMMSS";
var toYR = ToYYYMMDDHHMMSS.Substring(0, 4);
var toMN = ToYYYMMDDHHMMSS.Substring(4, 2);
var toDY =ToYYYMMDDHHMMSS.Substring(6, 2);
var toHR = ToYYYMMDDHHMMSS.Substring(8, 2);
var toMI = ToYYYMMDDHHMMSS.Substring(10, 2);
var motionPath = string.Format("{0}\\Catalogues\\{1}\\{2}\\{3}\\{4}\\{5}\\{6}", Shared.MOTION_DIRECTORY, camIndex, toYR, toMN, toDY, toHR, toMI);
Is there an alternative to using the substring? Can I use String.Format someway to get my desired result?
NB
I am so sorry for my poor phrasing of my question..
var ToYYYMMDDHHMMSS = "YYYMMDDHHMMSS";
I should have added that "YYYMMDDHHMMSS" is a timestamp that always changes
{apologies)
My guess is that your real code has a value of something like 20150225071945 - so not actually the literal YYYYMMDDHHMMSS. If that's the case, I would parse the value as a DateTime rather than extracting substrings:
DateTime dateTime = DateTime.ParseExact(text, "yyyyMMddHHmmss",
CultureInfo.InvariantCulture);
var motionPath = string.Format(#"{0}\Catalogues\{1:yyyy\\MM\\dd\\HH\\mm\\ss}",
Shared.MOTION_DIRECTORY, dateTime);
Note that the format string itself is a verbatim string literal, so you don't need to escape backslashes - but I've got \\ in the format string for the DateTime because the DateTime formatting code will treat \ as an escape.
An alternative would be to format each part of the date separately:
var motionPath = string.Format(#"{0}\Catalogues\{1:yyyy}\{1:MM}\{1:dd}\{1:HH}\{1:mm}\{1:ss}",
Shared.MOTION_DIRECTORY, dateTime);
Or use Path.Combine:
var motionPath = Path.Combine(Shared.MOTION_DIRECTORY,
"Catalogues",
dateTime.ToString("yyyy"),
dateTime.ToString("MM"),
dateTime.ToString("dd"),
dateTime.ToString("HH"),
dateTime.ToString("mm"),
dateTime.ToString("ss"));

Convert string (T,T-1,T 1 ) to DateTime in C#

I have a control which provide me the date selection in string format(T or T-1, T+1 etc ) and considering T as today date. I want to convert thestring selected Date(T or T-1, T+1) to DateTime.
Please Note that T(Today), T-1(Yesterday), T+1(Tommorrow) are received from the control and is in string format with one date at a time. Either T, T-1 or T+1 etc
I need to convert to T to something like 09/12/2013(for example with DD/MM/YYYY format)
T-1 to 08/12/2013 and T+1 to 10/12/2013.
Could you please suggest any standard/good approach to achieve this?
You could use a Regex to both verify the input and to extract the operator (+/-) and the number of days:
var input = "T - 51";
// input ca be "[whitespace]T[whitespace][+-][whitespace][number][whitespace]
// (whitespace is optional at every position)
var re = new Regex(#"\s*[T]\s*(?<op>[+-])\s*(?<days>\d+)\s*");
// check if input is valid
var match = re.Match(input);
if (match.Success)
{
// extract operator and number of days
var op = match.Groups["op"].Value;
var days = int.Parse(match.Groups["days"].Value);
// calculate resulting date
var date = DateTime.Now.AddDays(op == "+" ? days : -days);
}

spliting the string

I have an string like this
string strdate =#"5/2/2006";
Which is in a form of month/day/year.
I need to display it in a form of like this 02-05-2006.
How do i format the data like this?
If the value is like this: 12/28/2005, it should be displayed like this: 28-12-2010.
I know we should be splitting the data based on that we should do it.
I am not getting the syntax how to do it .
Any help would be great.
Parse the string into a DateTime and then use ToString with the right format to output it.
DateTime dt = DateTime.ParseExact(#"5/2/2006",
"MM/dd/yyyy",
CultureInfo.InvariantCulture);
string output = dt.ToString("dd-MM-yyyy");
I suggest reading up on custom and standard date and time format strings.
Read about how to parse DateTime string here: http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
Then you read about how to print it here: http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
#Kevin
var datearray = strdate.split('/');
string date = datearray[0] + "-" + datearray[1] + "-" datearray[2]
Issue 1
This wont work from days from 10th to 31st... It will add leading zero to each day.
12-05-2010 is good, but for ex. 12-021-2010 is not good.
Issue 2
Wrong order of MM-dd
You can use string.replace as such:
string newString = oldString.Replace('/', '-');
This will replace each '/' with '-' and create a new string, it will not replace it within the old string as strings are immutable.

Categories