Trimming a string from Excel - c#

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

Related

Parsing a string like "03/2020" to a DateTime variable

I have to parse a string, which always look like 03/2020 (so the format is MM/yyyy), to a DateTime variable.
How do I achieve it the most proper way? (Without splitting the string into substrings)
I already found the DateTime.ParseExact function, but I'm confused by the third parameter (culture-specific format information).
Is the DateTime.ParseExact the way to go or is there a better function/way to achieve the goal?
var inputString = "03/2020";
var inputStringFormat = #"MM/yyyy";
// var inputStringAsDateTime = ???
Edit 1
As additional info I have to say, that the string (inputString) is read from a barcode. So the separator in it is always the /.
Tim Schmelter explained in his answer, how to mask such separators.
It looks like I have to change my inputStringFormat variable to:
var inputStringFormat = #"MM'/'yyyy";
If the first day of the month is good for you, you can use DateTime.ParseExact:
var d = DateTime.ParseExact(inputString, inputStringFormat, CultureInfo.InvariantCulture);
Usually, i use ToDateTime method of Convert class. I have tested it, it's working.
string inputString = "03/2020";
DateTime datetime = Convert.ToDateTime(inputString));
It will give output like 3/1/2020 12:00:00 AM means it will gives you output according to your system's date format.
With such simple date format you can use
var inputArr = inputString.split(#"/");
var inputStringAsDateTime = new DateTime(inputArr[0], inputArr[1], 1);
however for culture you can use constant
CultureInfo.InvariantCulture

Regex.Replace - pattern for correcting date format

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

How to escape the GMT in "yyyyMMddThhmmss.000GMT"?

I am using JsonConverter attribute to set my datetime format but for the string
"yyyyMMddThhmmss.000GMT" I get dates like "19900321T20000.000G3T" because of the latter M. How do I escape these characters in my format string?
You can use:
"yyyyMMdd'T'HHmmss'.000GMT'"
I changed hh to HH since most (sane) people use a 24-hour count.
On the documentation Custom Date and Time Format Strings it is shown that aopstrophe characters like in 'string' can be used for literal string delimiters. Now I also put the T inside this delimiter, just for clarity, even if one capital T has no other meaning in a DateTime format string.
Use single quote to escape like:
"yyyyMMddThhmmss'.000GMT'"
Like:
string str = "19900321T20000.000GMT";
DateTime dt = DateTime.ParseExact(str,"yyyyMMddTHHmms'.000GMT'", CultureInfo.InvariantCulture);
Change hh to HH for 24 hours, also it appears your seconds are single digit values, so use a single s.
(I assume in your question original string you have GMT, not G3T)
You have 2 options to use your ...GMT part as string literal delimiter in custom date and format string:
".000GMT"
'.000GMT'
But I suggest to use single quotes because if you use double quotes, you need to escape your quotes with \ (because of escape sequence) or you can use verbatim string literal.
Do the same thing with T middle in your string as well.
Also use HH specifier which is for 24-hour clock and use s speficier instead of ss because you have 5 digit after your T that's why it doesn't accept HHmmss format.
The reason of you get G3T it is because M is has meaning of month of custom string format and that's why your GMT parsed as G3T.
string s = "19900321T20000.000G3T";
var dt = DateTime.ParseExact(s, "yyyyMMdd'T'HHmms'.000G3T'",
CultureInfo.InvariantCulture);
With double quotes;
string s = "19900321T20000.000G3T";
var dt = DateTime.ParseExact(s, "yyyyMMdd\"T\"HHmms\".000G3T\"",
CultureInfo.InvariantCulture);

How can I parse a DateTime from a string containing extra characters?

I have a string. The string is like this
Hello I am a Coder, My DOB is 12/09/2011.
I want to extract the date from this sentence. How do I do this using C#? I do not want regular expressions. This was an interview question asked to me recently.
This is my try
string myStr = "Hello 12/3/2013";
DateTime s;
DateTime.TryParse(myStr,out s);
Console.WriteLine(s);
I am getting the output as
01-01-0001 00:00:00
Both C# and JavaScript support regular expressions. You can use this pattern to find that section of the string:
\d{2}/\d{2}/\d{4}
Of course that doesn't ensure that it's a valid date, e.g. 13/88/0000 would match that pattern. You'd then have to parse the string using something like Date.Parse.
However, since you've stated regular expressions are not an option, here's a very crude one-liner:
var input = "Hello I am a Coder, My DOB is 12/09/2011.";
DateTime date = new DateTime();
input.Split().SkipWhile(s => !DateTime.TryParse(s, out date)).Any();
Console.WriteLine(date); // 12/9/2011 12:00:00 AM
Since you don't want to use REGEX, simply split the string on space and then use DateTime.TryParseExact to see if any string gets parsed as DateTime
string str = "Hello I am a Coder, My DOB is 12/09/2011";
string[] array = str.Split();//splits on space
string dateFormat = "M/d/yyyy"; //works with both single digit and double digit
//(day/month) for parsing
//or d/M/yyyy depending your date culture
DateTime tempDateTime;
var result = array.FirstOrDefault(r =>
DateTime.TryParseExact
(r,
dateFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.NoCurrentDateDefault,
out tempDateTime));
Your result would contain the Date string, and your tempDateTime would contain the parsed DateTime.

Formatting string to string Date Format .net 2.0

Given a string value eg "03252013" I need to convert this string to be in this format "DDMMYYYY".
Which function do you use? The result should be "25032013"
string myTestDate="03252013";
string resultDate=??
Thanks
Use DateTime.ParseExact method. Then use ToString to convert to appropriate format.
var dt = DateTime.ParseExact("03252013", "MMddyyyy", CultureInfo.InvariantCulture);
var result = dt.ToString("ddMMyyyy"); //25032013
string resultDate = DateTime.ParseExact(myTestDate, "MMddyyyy", CultureInfo.InvariantCulture).ToString("ddMMyyyy");
Simply parse then re-format:
string input = "03252013"
DateTime date = DateTime.ParseExact(input, "MMddyyyy", CultureInfo.InvariantCulture);
string resultDate = date.ToString("ddMMyyyy");
If your needs really are that simple I would consider just switching the values around...
string input = "03252013";
string output = input.Substring(2, 2) + input.Substring(0, 2) + input.Substring(4, 4);
...dont forget to validate the input before using substring (checking the length is 8 will probably be enough)
NOTE: If it is likely that your input or output formats will change then it would be more ideal to do the DateTime.Parse technique as suggested by many others. But if this is really the only situations then this method should provide better performance... slightly ;)
You, can use the Help of following code part to convert.
string resultDate = DateTime.ParseExact(myTestDate, "MMDDYYYY", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None).ToString("DDMMYYYY");
Use this:
resultDate = DateTime.Parse(myTestDate,"d").toString();
"d" is a format provider that says to farmat the date like this: DD/MM/YYYY

Categories

Resources