RegEx for placeholder (mmddyyyy) with no particular order - c#

I have a string that looks like this: myFile{ddmmyyyy}.csv and a C# DateTime object. I need to substitute the correct day/month/year from the DateTime into the string. However the problem lies in the fact that the parameters can be in a different order AND not all of them might be present.
e.g. All of these are valid use cases:
myFile{ddmmyyyy}.csv
myFile{mmddyyyy}.csv
myFile{mmyyyy}.csv
myFile{yyyymm}.csv
Any suggestions/ideas on the regex that I could use to find/substitute these would be greatly appreciated!
EDIT: Just to be clear, I get the actual string that has "mmddyyyy" in there (characters, not the corresponding numbers) where "mm" needs to be substituted for the month number (10 representing October, for example) for the DateTime received.

private static string FormatFilename(string pattern, DateTime dt)
{
return Regex.Replace(pattern, #"\{(.*)\}", match =>
{
string format = match.Result("$1").Replace("m", "M");
return dt.ToString(format, CultureInfo.InvariantCulture);
});
}
Then just call it like this (for example):
string input = "myFile{ddmmyyyy}.csv";
DateTime dt = new DateTime(2013, 1, 4);
string filename = FormatFilename(input, dt);
Update
It is possible to do this without a regex:
private static string FormatFilename(string pattern, DateTime dt)
{
return string.Format(pattern.Replace("{", "{0:").Replace("mm", "MM"), dt);
}
But I think the other version is cleaner and more resilient to input variation.

would \w+\d+.csv work for you?

Just match
#"myFile\d{8}.csv"
And use DateTime.ParseExact or DateTime.TryParseExact to parse it (use the overload that accepts an array of formats)

Related

What is a less Kludgy way to Conditionally Prepend a "0" to dateTime Elements?

I want my string YearMonthDayHourMinuteSecondMillisecond to be of this format ("0" prepended where necessary):
20140227142807
...but this:
string YearMonthDayHourMinuteSecond = string.Format("{0}{1}{2}_{3}{4}{5}", dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
...gives me "2" (instead of "02") for February, etc. such as:
2014227142807
I can solve it this way:
string YearMonthDayHourMinuteSecondMillisecond = string.Format("{0}{1}{2}_{3}{4}{5}{6}", dt.Year, ConditionalZeroForepad(dt.Month), ConditionalZeroForepad(dt.Day), ConditionalZeroForepad(dt.Hour), ConditionalZeroForepad(dt.Minute), ConditionalZeroForepad(dt.Second);
private string ConditionalZeroForepad(string s)
{
if (s.Length < 2)
{
return string.Format("0{1}", s);
}
}
...but that's 9X Uglier than a Bag of Butts.
What is a more genteel way to accomplish this?
Don't use string.Format at all - use DateTime.ToString():
string text = dt.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture);
Or to just go down to seconds:
string text = dt.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
(Your variable name suggests you want milliseconds, but your sample suggests you don't.)
Note the use of CultureInfo.InvariantCulture to ensure you always use the Gregorian calendar, even if the current culture of the thread is one which has a different default calendar. (Obviously if you want a different calendar, that's a different matter.)
See custom date and time format strings for more information.
You need to use a string format like:
var str = string.Format("{0:D2}", 2);
Value of str: 02
The D2 portion tells the formatter to make sure there is at least two digits in the formatted number. See this MSDN page for more on Custom Numeric Format Strings
But providing a date time format to DateTime.ToString is a better solution then trying to compose the format you want from the individual parts.
string YearMonthDayHourMinuteSecondMillisecond = dt.ToString("yyyyMMddHHmmss")
You could use ToString() with a format parameter such as dt.Month.ToString("D2")

Remove '0' (Number) from DateTime Month and Day (String)

Can anybody tell me the best approach or solution on how I would do the following?
I have a DateTime (as String) in following format:
string test = "21.12.2013";
How could I now remove all zero's from the month and day but still 'keep' the DateTime Logic:
//Example 1
string input = "06.10.2013" // 6th October
string output = "6.10.2013" //only remove '0' from the day
//Example 2
string input = "01.09.2012" // 1st September
string output = "1.9.2012" //remove from month and day
//Example 3
string input = "20.10.2011" // 20th October
string output = "20.10.2011" //should (must) stay!
I can also parse to DateTime if that would be make it easier but yeah I hope you got my idea...
Any help appreciated!
Parsing your string into DateTime and getting it back to string using ToString with desired patter seems to be the easiest way to go:
public static string GetRidOfZeros(string input)
{
var dt = DateTime.ParseExact(input, "dd.MM.yyyy", CultureInfo.InvariantCulture);
return dt.ToString("d.M.yyyy", CultureInfo.InvariantCulture);
}
Little testing, with your sample data:
var inputs = new List<string> { "06.10.2013", "01.09.2012", "20.10.2011" };
var outputs = new List<string> { "6.10.2013", "1.9.2012","20.10.2011" };
if(outputs.SequenceEqual(inputs.Select(d => GetRidOfZeros(d))))
Console.WriteLine("Output is OK");
else
Console.WriteLine("Collections does not match.");
Prints Output is OK.
DateTime.Parse(input).ToString("d.M.yyyy")
As you said, parsing to DateTime first would probably make things easier, since then you can just use:
myDateTime.ToString("d.M.yyyy");
When you parse it you can use ToString to format it any way you like:
var date = "06.10.2013";
DateTime parsed = DateTime.ParseExact(date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
var noZerosHere = parsed.ToString("d.MM.yyyy");
A decent "catch-all" method (that will work not just on DateTime but ANY kind of string) would be to split the string up, take out leading zeroes and then put the pieces back together again.
string input = "01.09.2012";
string[] values = input.Split(".");
string[] modifiedValues = values.Select(x => x.TrimStart('0');
string output = String.Join(".", modifiedValues);
You can adjust the delimiters for different representations of DateTime, e.g. those that use slashes (01/09/2012) or are written in a different order.

Format to be changed in strings

My string contains the value: 08/20/2012-10.32.19
I want the output in string datatype itself as 08/20/2012 10:32:19 [format is MM/dd/yyyy HH:mm:ss].
Please help!!
You may convert the string to DateTime and then use .ToString() with the required format.
DateTime dt = DateTime.ParseExact("08/20/2012-10.32.19", "M/d/yyyy-HH.mm.ss",CultureInfo.InvariantCulture);
string test = dt.ToString("MM/dd/yyyy HH:mm:ss");
Test will have
08/20/2012 10:32:19
EDIT: based on the comment
You may specify multiple date formats and then parse accordingly.
string[] formats = new string[] { "M/d/yyyy-HH.mm.ss", "yyyy-M-d-HH.mm.ss" };
string dtTest1 = DateTime.ParseExact("08/20/2012-10.32.19",
formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None)
.ToString("MM/dd/yyyy HH:mm:ss");
Or in a single line
string dtTest2 = DateTime.ParseExact("08/20/2012-10.32.19",
new string[] { "M/d/yyyy-HH.mm.ss", "yyyy-M-d-HH.mm.ss" },
CultureInfo.InvariantCulture,
DateTimeStyles.None)
.ToString("MM/dd/yyyy HH:mm:ss");
This will satisfy your both case of dates:
08/20/2012-10.32.19
2012-08-20-10.32.19
You may use very simple becouse your string only require fiormating
String a="08/20/2012-10.32.19".Replace('-', ' ').Replace('.', ':');
I hope this work for you
We have various inbuilt format like ToLongDateTime, ToShortdateTime in .Net
string formatDate = txtdte.ToShortDateTime();
This returns string so no need of any other conversion. If you are specific about your format, ToString takes parameters like ToString("dd/mm/yyyy")

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;

Converting string format to datetime in mm/dd/yyyy

I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Please help.
You are looking for the DateTime.Parse() method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01/01/2001");
Which will give you a DateTime typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
You need an uppercase M for the month part.
string strDate = DateTime.Now.ToString("MM/dd/yyyy");
Lowercase m is for outputting (and parsing) a minute (such as h:mm).
e.g. a full date time string might look like this:
string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");
Notice the uppercase/lowercase mM difference.
Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.
public static class DateTimeMyFormatExtensions
{
public static string ToMyFormatString(this DateTime dt)
{
return dt.ToString("MM/dd/yyyy");
}
}
public static class StringMyDateTimeFormatExtension
{
public static DateTime ParseMyFormatDateTime(this string s)
{
var culture = System.Globalization.CultureInfo.CurrentCulture;
return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
}
}
EXAMPLE: Translating between DateTime/string
DateTime now = DateTime.Now;
string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();
Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.
System.Globalization.CultureInfo.CurrentCulture.
The only easy way you can do is to roll a custom extension method.
Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.
Solution
DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)
I did like this
var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
You can change the format too by doing this
string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");
// this change the "/" for the "-"
The following works for me.
string strToday = DateTime.Today.ToString("MM/dd/yyyy");

Categories