Extract date time from file name with extension - c#

I want to extract date from the string.
String : _21_BT_Txn_Details_1-Aug-2015_1031389ACF6.zip
How to do it?

Try this:
\d{1,2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}
Demo and explanation of regex symbols: https://regex101.com/r/lW9yI3/2
Assumptions:
Day could be one or two digits
Year is always four digits
Standard three-letter abbreviations are use for the month

You can use the following code that can extract more than 1 dates inside the string like the one you provided:
var txt = "_21_BT_Txn_Details_1-Aug-2015_1031389ACF6.zip";
DateTime dt;
var res = txt.Split('_').Where(p => DateTime.TryParse(p, out dt)).ToList();
Or, if you always have the date in the above format (day-MON-year), use
DateTime.TryParseExact(p, "d-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)
There is no need for a regex here.

Related

How to parse date from string using ParseExact?

I'm trying to parse a date from a string formatted as the following "17/9/2020, 13:00:00" as a valid DateTime object, but after trying to use .ParseExact and setting the date pattern i'm getting the error:
String '17/9/2020, 13:00:00' was not recognized as a valid DateTime..
By using .ParseExact i'm trying to do the following:
DateTime.ParseExact(quando.quando, "dd/MM/yyy, HH:mm:ss", null)
you have 1 M too much and 1 y too few:
DateTime.ParseExact("17/9/2020, 13:00:00", "dd/M/yyyy, HH:mm:ss", null)
the format MM expects an input of always two digits for the month like 09 (september)
If you take only 1 M it will also parse a 2 digit month like december:
DateTime.ParseExact("17/12/2020, 13:00:00", "dd/M/yyyy, HH:mm:ss", null)
EDIT: taking this from Jon Skeets comment: you should probably also use a single d for days since your date string will likely exhibit the following format "7/9/2020, 13:00:00".
DateTime.ParseExact("7/9/2020, 13:00:00", "dd/M/yyyy, HH:mm:ss", null)
Your format isn't correct. See an example here:
https://dotnetfiddle.net/2ppjvX
You should use this format "dd/M/yyyy, HH:mm:ss". "MM" expects 2 digist like "09". Also 4 "y" symbols are required.

Regex to find dates before a certain year

So i have a string that has different dates and I want to only find dates on or before 1998. The format in the string is dd-mm-yyyy. This is what I have so far
Regex test = new Regex(#".*\d\d-\d\d-(18|19)\d\d");
I just don't know how can I make it so that it only finds dates on or before 1998.
Years 1000 to 1999 can be matched with 1\d\d\d
Years 1000 to 1998 can be matched with (1[0-8][0-9]{2}|19[0-8][0-9]|199[0-8])
No I can't write them out that quick I used: http://gamon.webfactional.com/regexnumericrangegenerator/
Personally, I might be tempted to do in two steps, find ones in likely range (1000-1999) then actually parse them and check the actual date, particularly if your requirements get any more complex.
This one is a little more in depth, will also constrain months to 1-12, and days 1-31, will allow 01-09 for both, and goes up to 12-31-1998
#"(?<!\d)(?:1[0-2]|0?[1-9])-(?:[0-2]?[1-9]|3[0-1])-1\d(?:\d[0-8]|[0-8]\d)"
I agree with #jmargolisvt that it seems this would be best solved with the Datetime object. But, if there's some reason you must use regex ...
You can use #weston's original idea to restrict from 1000 to 1999:
.*\d{2}-\d{2}-1\d{3}
But add a negative-lookahead to eliminate 1999 explicitly:
.*\d{2}-\d{2}-(?!1999)1\d{3}
Here's another example that validates the date a little bit, not allowing month numbers or day numbers that can't exist.
(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2\d|3[01])-(?:1\d\d[0-8])
https://regex101.com/r/Ml5WTK/1
I suggest combining regular expressions and Linq:
Regex extracts matches that can be date
Linq ensures (via DateTime.TryParseExact) that they are date and filter out years
Implementation
// Expected date; invalid date; date out the range
string source = "20-10-1950 29-02-1955 23-02-2097";
var result = Regex
.Matches(source, "[0-3][0-9]-[01][0-9]-[0-2][0-9]{3}")
.OfType<Match>()
.Select(match => {
DateTime dt;
bool valid = DateTime.TryParseExact(match.Value,
"dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out dt);
return new {
valid = valid,
value = dt,
};
})
.Where(item => item.valid && item.value.Year <= 1998)
.Select(item => item.value);
// 20.10.1950 12:00:00
Console.Write(string.Join(Environment.NewLine, result));

Datetime conversion in C# - using formats

I need to convert a String to DateTime format, for this I just tried like
DateTime.ParseExact(DateOfBirth,"MM/dd/yyyy",CultureInfo.InvariantCulture);
it's working fine when I pass the value like 05/30/2012.
But if I try to pass the value as 5/30/2012 its showing error:
String was not recognized as a valid DateTime
To fix this I tried like
DateTime.ParseExact(String.Format("{0:MM/dd/yyyy}", DateOfBirth), "MM/dd/yyyy",
CultureInfo.InvariantCulture);
it's still not working. Here If I try String.Format("{0:MM/dd/yyyy}", DateOfBirth) for the value 5/30/2012 its showing the same format instead of 05/30/2012.
How can I fix this, can anyone help me here...
check this link
string to DateTime conversion in C#
Use M/d/yyyy instead of the format specifier you're using. Using only a single M matches months with leading zeros as well. This is also true for d.
assuming your DateOfBirth string is always separated by slashes, you could try something like this:
string[] dateParts = DateOfBirth.Split('/');
DateTime.ParseExact(string.Format("{0:00}", dateParts[0]) + "/" + string.Format("{0:00}", dateParts[1]) + "/" + string.Format("{0:0000}", dateParts[2]));
I think the issue is the format string can't be recognized since DateOfBirth is not a DateTime object. Thus, you enforce formatting by reformatting the string yourself
There is an overload which might be of your interest
DateTime.ParseExact(DateOfBirth,
new[] { "MM/dd/yyyy", "M/dd/yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.None);
This should help you take care of single as well as two digit month part (since 5 is failing for you as the format is MM)
Since you have separators in your string (ie /), you can just do;
DateTime.ParseExact(DateOfBirth,"M/d/yyyy",CultureInfo.InvariantCulture);
That will parse either single or double digit days/months. When you use MM/dd/yyyy, you're requiring them both to be double digit numbers, and that's obviously not what you want in this case.
Try just "d" instead of "MM/dd/yyyy".
So, the statement should be:
var date = DateTime.ParseExact(DateOfBirth, "d", CultureInfo.InvariantCulture);
The documentation for this is here:
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
Edit
Oops, I misread the documentation. It should be "M/d/yyyy".
In case you need to make it culture-independent..
var dateTimeFormat = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentUICulture.Name).DateTimeFormat;
dateTimeFormat.ShortDatePattern =
Regex.Replace(Regex.Replace(dateTimeFormat.ShortDatePattern, "[M]+", "MM"), "[d]+", "dd");
var newDate = date.HasValue ? date.Value.DateTime.ToString("d", dateTimeFormat) : null;

How would I make a datetime into a specific custom format?

Say the current date is 1st Mar 2010, I want to display it like this...
20100301 so like first 4 digits = year, 2 digits = Month, 2 digits = day
is there an easy way to do this?
use format
yourdatetimeObj.ToString("yyyyMMdd");
Ref: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Something like
dateTimeObject.ToString("yyyyMMdd");
See String Format for DateTime
var mydate = DateTime.Now; // Whatever you want.
mydate.ToString("yyyyMMdd");
Look at DateTimeFormatInfo for the other custom format strings you can use.
You can either use the ToString() implementation of the DateTime class, like the examples already given, or use a format string to display it along with other information, like so:
var now = DateTime.Now;
var msg = String.Format("Now: {0:dd/MM/yyyy}", now);
Or
Console.Write("Now: {0:MM/dd/yyyy}", now);

Split the date in c#

For Ex
You date enter in the various form in textbox
12/Augest/2010
augest/12/2010
2010/12/Augest
and out put is
three textbox First is day show= 12
textbox second is Months show= augest
textbox third is Year show= 2010
To parse/validate against three expected formats, you can use something like below. Given the pattern, once you know it is valid you could just use string.Split to get the first part; if you need something more elegant you could use TryParseExact for each pattern in turn and extract the desired portion (or re-format it).
string s1 = "12/August/2010",
s2 = "August/12/2010",
s3 = "2010/12/August";
string[] formats = { "dd/MMMM/yyyy", "MMMM/dd/yyyy", "yyyy/dd/MMMM" };
DateTime d1 = DateTime.ParseExact(s1, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None),
d2 = DateTime.ParseExact(s2, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None),
d3 = DateTime.ParseExact(s3, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None);
Use DateTime.Parse(String, IFormatProvider) or DateTime.ParseExact to convert the string into DateTime.
Then you can extract the day, month and year using the corresponding properties.
Use DateTime.Parse(s). See MSDN
Then you can get the individual parts of a DateTime structure.
e.g.
DateTime date = DateTime.Parse("some input date string");
string day = DateTime.Day.ToString();
string month = DateTime.Month.ToString();
string year = DateTime.Year.ToString();
date dt date.Parse(txtBox.text);
txtBox1.Text = dt.Day.ToString();
txtBox2.Text = dt.ToString("MMM");
txtBox3.Text = dt.Year.ToString();
date.Parse might throw depending on the string you give it, but then you can fall back by trying to parse it using a different culture.
Edit: Added an M

Categories