I am currently working on a dotnet core 3.0 app that needs to parse different datetime strings into a System.DateTime. My development environment is VS2019 on Windows 10 but the application will run on Raspbian (debian-arm) later. Let's look into this example code:
// input string
const string testdate = "Jan. 1 01:05:26";
var dateFormats = new[] { "MMM. d HH:mm:ss", "MMM. dd HH:mm:ss" };
var dateTime = DateTime.ParseExact(testdate, dateFormats, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal);
// output should be: 01.01.2020 01:05:26
Console.WriteLine($"Date: {dateTime.ToString("dd.MM.yyyy HH:mm:ss")}");
While this works as expected in development under windows 10, it will throw an exception on raspbian:
System.FormatException: String 'Jan. 1 01:05:26' was not recognized as a valid DateTime.
I already checked the CultureInfo but both of the systems are set to the same one. Is there something i am missing here? How can i ensure that these DateTimes are parsed correctly on raspbian?
Update:
I just noticed the year part of the date is missing. Is this the reason for that exception? but why is it working on windows and assuming the current year?
Solution:
As nl-x suggested, i tried printing the current datetime formated as my input dateformats. and there it was:
DateTime.Now.ToString("MMM. d HH:mm:ss")
// Windows output: Jan. 2 16:29:45
// Raspbian output: Jan.. 2 16:29:45
Apparently raspbian already includes the trailing dot in "MMM" format while windows does not. Changing my date formats to:
var dateFormats = new[] { "MMM. d HH:mm:ss", "MMM. dd HH:mm:ss", "MMM d HH:mm:ss", "MMM dd HH:mm:ss" };
now works both in windows and linux. thank you!
Try using invariant culture, or set the culture explicitly.
Your local system might be running in a different language than your Linux system.
What "Jan" is on your local system, might be different on the Linux system.
Try printing a date with the current format from your linux, and see if it uses something else for "Jan" EG dateTime.Now.ToString("MMM. d HH:mm:ss", "MMM. dd HH:mm:ss")