Convert string (T,T-1,T 1 ) to DateTime in C# - 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);
}

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.

Get DateTime from FileName

I have a file named test-2000_01_02-10_12_14.xml.
How do I only get the date from the file?
I was able to get the date if the file has this name: 2000_01_02-10_12_14
with this (b is a StorageFile):
DateTime dateVal;
bool parsed = DateTime.TryParseExact(b.DisplayName,
"yyyy_MM_dd-H_mm_ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dateVal);
I then tried to change yyyy_MM_dd-H_mm_ss to something like this *-yyyy_MM-dd-H-mm_ss but it does not seem to be the solution
There are a boatload of ways to do this, it really rather depends on how regular the naming of your files is - is there always some junk text followed by a hyped, then the year?
Post up another 10 different examples if you want more tailored advice. Here's a way for the one you've posted:
DateTime.TryParseExact(
Path.GetFileNameWithoutExtension(b.DisplayName.Substring(b.DisplayName.IndexOf('-')+1)),
"yyyy_MM_dd-H_mm_ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dateVal
);
This uses Substring with only one argument (no length) to remove everything after the first hyphen up to the end of the string, and GetFileNameWithoutExtension to remove the .xml - this effectively turns anythinghere-2000_01_01-00_00_00.xml into 2000_01_01-00_00_00 ready for parsing
I could also have gone for a .Remove("last index of period") type thing but it does get a bit messy because you have to subtract the start Index of the hyphen etc
MJWill's comment about splitting on hyphen is also a good one - you could split then take the [1] and [2] indexes and join then back together for parsing..
Lastly don't forget that the file itself might have a created date that is already a good candidate for the date of creation rather than the filename (which might be mangled by humans) so long as it hasn't been transmitted somewhere and re-saved. Take a look at the FileInfo.CreationTime property for that - https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netframework-4.8
First, we have to extract (match) the datetime part from a file name:
using System.Text.RegularExpressions;
...
// Aggravated task: dots and minuses within file's name
string source = #"bla-bla-bla-test.me-2000_01_02-10_12_14.xml";
string datetime = Regex.Match(
Path.GetFileNameWithoutExtension(source),
"[0-9]{4}_[0-9]{2}_[0-9]{2}-[0-9]{2}_[0-9]{2}_[0-9]{2}$").Value;
Then we can parse it
if (DateTime.TryParseExact(
datetime,
"yyyy_MM_dd-H_m_s",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out DateTime result) {
// result is the parsed date
}
else {
// File doesn't contain valid date and time
}
I would suggest you to use regular expression assuming that your file name will be always following the same format you can do something like this:
var pattern = #"\d{4}_\d{2}_\d{2}-\d{2}_\d{2}_\d{2}";
var fileName = "test-2000_01_02-10_12_14.xml";
var match = new Regex(pattern);
var result = match.Match(fileName);
if (result.Success)
{
DateTime.TryParseExact(result.Value,
"yyyy_MM_dd-HH_mm_ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out DateTime dateVal);
}

C# - Extract Date from String using StreamReader

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();
}

"Input string was not in a correct format" error in Lambda Expression

First I should mention that I know there are several questions similar to mine, but none of them could help me.
I want to compare two dates which are in two different SQL table and I'm using Lambda Expression.
My code:
var itemStartDate = new ItemsBusiness().GetList<Item>(i => Convert.ToInt64(i.StartDate.Replace("/", "")) < Convert.ToInt64(tdpStartDate.Text.Replace("/", "")));
However when I run the program, this exception shows up:
Input string was not in a correct format. When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
The line which catches the exception is in another form:
try
{
int inputVal = Convert.ToInt32(value.Trim().Replace("px", ""));
myLabelWidth = inputVal.ToString();
}
p.s: My dates format is like this: "2010/06/20"
This is what I think is happening. I assume that you turn your date into a string like this:
var StartDate = DateTime.Now.Date.ToString();
var tdpStartDate = DateTime.Now.Date.ToString();
var result = Convert.ToInt64(StartDate.Replace("/", "")) < Convert.ToInt64(tdpStartDate.Replace("/", ""));
This will fail with the error you got because the Date is in a format with letters when representing the month.
What you can do is simply to format the Date to include nothing but digits:
var StartDate = DateTime.Now.Date.ToString("ddMMyyyy");
var tdpStartDate = DateTime.Now.Date.ToString("ddMMyyyy");
var result = Convert.ToInt64(StartDate) < Convert.ToInt64(tdpStartDate);
This does not throw the exception like before

C# - How to format datetime to remove trailing zeros

I'm setting up an orchestration class that handles multiple actions as one big transaction. For each of these transactions I give them the same time-stamp instantiated at the beginning of the orchestration.
I user the following line:
var transactionTimestamp = DateTime.UtcNow.ToString("o");
I have a constraint in the system that dictates that the time stamp cannot have any trailing zeros.
For example:
2013-06-26T19:51:38.0083980Z //bad
2013-06-26T19:51:38.008398Z //good
2013-06-26T19:51:38.0083988Z //good
The built-in DateTime format "o" is comparable to the custom format of: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK". If you just use that format, but replace the lower-case f's with upper case ones, there will be no trailing zeros.
ie
DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFFK");
Custom date and time format strings
You can achieve this fairly easily using Regex. Here's one way.
string result = Regex.Replace("2013-06-26T19:51:38.0083980Z", "0+Z$", "Z");
// result == "2013-06-26T19:51:38.008398Z"
string result2 = Regex.Replace("2013-06-26T19:51:38.0083988Z", "0+Z$", "Z")
// result2 == "2013-06-26T19:51:38.0083988Z"
I would write my own help method like;
public string GetDtString(DateTime dt)
{
RegEx rgx = new RegEx("[1-9]0+Z\b");
return rgx.Replace(dt.ToString("o"), System.String.Empty);
}
It basically just returns the dt string with all 0's which occur after a digit 1-9 and before Z\b (Z followed by a word boundary) with an empty string.

Categories