Regex.Replace - pattern for correcting date format - c#

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");

Related

Parse a String date like this: March 03/12/2016 to just 03/12/2016

I need to do a simple parse the strip out the actual word March (or whatever month it is) from a data saved to a string like this: "March 03/12/2016".
The ending results need to be a string such as: "03/12/2016".
I have been looking through date time formatters and I am not finding a simple method to strip out a month. I was thinking of just cutting the string down to count 11 characters from right to left and then just trimming out the rest but I feel like that is sloppy and there is probably a date format option out there that I'm just not finding.
Any Suggestions?
Just do this:
string input = "March 03/12/2016";
string output = input.Substring(input.IndexOf(' ') + 1);
Another approach:
string result = input.Split(' ')[1];
string input = "March 03/12/2016";
string output;
int index = input.IndexOf(' ');
if(index >= 0) //Checks if there exists a space
{
output = input.Substring(input.IndexOf(' ') + 1);
}
You need to first check if there will always be a space, because if it does not exist it will present problems since input.IndexOf does not have error handling.
Assuming that month name is proper English name for the month, you can use MMMM to extract month name. Then, you can just format the date however you wish.
var date = "March 03/12/2016";
var parsedDate = DateTime.ParseExact(date, "MMMM MM/dd/yyyy", new CultureInfo("en-US"));
Console.WriteLine(parsedDate.ToString("MM/dd/yyyy"));
See in dotnetfiddle.net.
Bear in mind that if months parsed from the date will be different, eg. October 03/12/2016, exception will be thrown.

Extracting a Date value from a string

Forum.
My code reads from an excel file and gets the following string in a variable 'textContainingDate':
"Employee Filter: All Employees; Time Entry Dates: 01/07/2016-01/07/2016; Exceptions: All Exceptions"
What I would like to do is extract the date value from the string. Although there are two dates to be read as a date range, the two dates will always be the same. My thought is, regardless of the scenario, I will be satisfied with the first date I come across.
var dateTime = DateTime.ParseExact(textContainingDate, "MM/dd/yyyy", CultureInfo.CurrentCulture);
I tried using the above statement, which I pieced together from other stackoverflow questions and Googled articles. From what I have read, I believe it fails because it is expecting only a date string.
Any advising on a solution and/or direction towards what text to read to find a solution is appreciated.
You can use Regex.Match to get the first date string you meet. This method returns the first substring that matches a regular expression pattern in an input string.
string stringWithDate = "Employee Filter: All Employees; Time Entry Dates: 01/07/2016-01/07/2016; Exceptions: All Exceptions";
Match match = Regex.Match(stringWithDate, #"\d{2}\/\d{2}\/\d{4}");
string date = match.Value;
if (!string.IsNullOrEmpty(date)) {
var dateTime = DateTime.ParseExact(date, "MM/dd/yyyy", CultureInfo.CurrentCulture);
Console.WriteLine(dateTime.ToString());
}
What the regular expression \d{2}\/\d{2}\/\d{4} does:
var regex = new Regex(#"\d{2}\/\d{2}\/\d{4}");
foreach (Match m in regex.Matches(line))
{
DateTime dt;
if (DateTime.TryParseExact(m.Value, "MM/dd/yyyy", null, DateTimeStyles.None, out dt))
remittanceDateArr[chequeNo - 1] = dt.ToString("MM/dd/yyyy");
rtbExtract.Text = rtbExtract.Text + remittanceDateArr[chequeNo - 1] + "\n";
}

Convert Date format from dd-mmm-yyyy (16-May-2013) to mm/dd/yyyy (09/12/2013)

I want to convert date format from dd-mmm-yyyy (16-May-2013)
to date format mm/dd/yyyy (09/12/2013).
I am using this code. But still not able to get the correct value. the month value is becoming zero.
string dt = DateTime.Parse(txtVADate.Text.Trim()).ToString("mm/dd/yyyy");
In the above code txtVADate is the TextBox Control Which is giving date format
like
dd-mmm-yyyy example (16-May-2013).
Any Answers are appreciable.
The format specifier for month is MM not mm, try using MM/dd/yyyy. Also when using a custom format it's best to pass InvariantCulture to avoid any clashes with the current culture your app is running under i.e.
DateTime.Parse(txtVADate.Text.Trim()).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
See Custom Date and Time Format Strings.
Use capital M letter.
m - minute
M - month
You have to use MM instead of mm and CultureInfo.InvariantCulture as second parameter
string dt = DateTime.Parse(txtVADate.Text.Trim()).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
The slashes / mean: "replace me with the actual current date-separator of your culture-info".
To enforce / as separator you can use CultureInfo.InvariantCulture:
string dt = DateTime.Parse(txtVADate.Text.Trim())
.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
MSDN:
/
The date separator defined in the current
System.Globalization.DateTimeFormatInfo.DateSeparator property that is
used to differentiate years, months, and days.
( you also have to use MM instead of mm since lower case is minute whereas uppercase is month )
string dt = datatime.toshortdatestring`
Here is your solution.
using System.Globalization;
string dt = DateTime.Parse(txtDate.Text.Trim()).ToString("mm/dd/yyyy", CultureInfo.InvariantCulture);
also can be done like this
public string FormatPostingDate(string txtdate)
{
if (txtdate != null && txtdate != string.Empty)
{
DateTime postingDate = Convert.ToDateTime(txtdate);
return string.Format("{0:mm/dd/yyyy}", postingDate);
}
return string.Empty;
}

Why does a call to DateTime.TryParseExact fail with input "1212012" using the format string "Mddyyyy"

I have a date string that is coming in as what I believe to be Mddyyyy. However, TryParseExact doesn't seem to be working. Here's the sample code that fails:
string datestring = "1212012";
DateTime td;
if (DateTime.TryParseExact(datestring, "Mddyyyy", new CultureInfo("en-US"), DateTimeStyles.None, out td))
{
Console.WriteLine(td.ToShortDateString());
}
else
{
Console.WriteLine("Invalid Date String");
}
That same code works if there's a leading zero, but I would think then that the leading zero would only work with a formatting string of MMddyyyy.
Here I propose an explanation and provide evidence for the proposal.
Proposed Explanation: The parser internally uses the format string to create a regular expression that contains a greedy quantifier (which means, in this case, it prefers to match 2-digit months over 1-digit months). The M in the OP's format string becomes something like \d{1,2} (though that would match months numbered from 0 to 99!) in the parser's internal regular expression.
Evidence: If you move the month to the end of both the data and the format string, the greedy quantifier cannot obtain more than 1 digit and so it matches the month as desired:
string datestring = "2120121";
DateTime td;
if (DateTime.TryParseExact(datestring, "ddyyyyM", new CultureInfo("en-US"), DateTimeStyles.None, out td))
{
Console.WriteLine(td.ToShortDateString());
}
else
{
Console.WriteLine("Invalid Date String");
}
Bottom Line: Don't rely on undocumented behavior. Always use unambiguous data, i.e., 2-digit months.

Trimming a string from Excel

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

Categories

Resources