1

I have a system where the log file is generated with the current datetime at the beginning of each line.

eg.

LogUtil.Logger(DateTime.ToString("yyyy/MM/dd") + "|" + "My Message Here");

Depending on the culture this log file can result in a different separator between the year, month and day.

eg.

2015/11/19  or  2015.11.19

I am writing a separate utility which takes this resulting log file and parses it, sending other information to a 3rd party.

Since the date format is different, how can i get it to parse it correctly each time.

Currently im using:

DateTime.TryParseExact(line.Substring(0, 10), "yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out Date);

This format specifier only correctly formats 2015/11/19

CathalMF
  • 9,705
  • 6
  • 70
  • 106

2 Answers2

2

You can pass multiple formats to DateTime.TryParseExact. Use that overload.

DateTime.TryParseExact(line.Substring(0, 10), 
                    new[] {"yyyy/MM/dd", "yyyy.MM.dd"}, 
                    CultureInfo.InvariantCulture, 
                    DateTimeStyles.None, 
                    out Date);

This should for both formats: 2015/11/19 or 2015.11.19

Habib
  • 219,104
  • 29
  • 407
  • 436
  • What if Mr. Random Customer decides to go into his regional settings and changes his date formatting to use a * instead of . or / – CathalMF Nov 19 '15 at 16:09
  • @CathalMF: The root of your problem lies in the fact that you're letting users' settings impact the format of your log file. Until you fix that, any approach for parsing the log file is going to be fragile. – StriplingWarrior Nov 19 '15 at 16:12
  • @CathalMF, you can't program against all the possible options, You can request the the Separator property through [`DateTimeFormatInfo.DateSeparator`](https://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.dateseparator(v=vs.110).aspx) property , see if that exists in your input string, replace it with the usual one from your formats and do the parsing. But the best option would be to use a single format, usually application log is for you, it is not for the user. – Habib Nov 19 '15 at 16:14
0

If you can tell which culture was used to generate the given log file, use that culture instead of InvariantCulture.

var culture = CultureInfo.GetCultureInfoByIetfLanguageTag("tr-TR"); // e.g.
DateTime.TryParseExact(line.Substring(0, 10), 
                "yyyy/MM/dd", 
                culture, 
                DateTimeStyles.None, 
                out Date);

To prevent future issues, I strongly recommend producing your log file output with an invariant culture in the first place.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315