slandau
slandau

Reputation: 24052

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?

Upvotes: 0

Views: 472

Answers (6)

Jon Skeet
Jon Skeet

Reputation: 1500675

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.

Upvotes: 2

Arbiter
Arbiter

Reputation: 1024

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

Upvotes: 0

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112372

s = s.Substring(1, s.Length-2);

Upvotes: 0

Ray
Ray

Reputation: 46585

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

Upvotes: 2

Tom Morgan
Tom Morgan

Reputation: 2365

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?

Upvotes: 0

ken2k
ken2k

Reputation: 48985

string myString = "\"11/01/2011 16:00\"";
DateTime time = DateTime.Parse(myString.Substring(1, myString.Length - 2));

Upvotes: 0

Related Questions