Search code examples
c#windows-task-schedulersql-server-agent

Difference in DateTime.TryParse when running app through SQL Agent and Task Scheduler


This has got me stumped... I have an application that I run from SQL Server Agent (Operating System cmdExec) that behaves differently to when it's run through Windows Task Scheduler or directly running the exe.

The C# code that fails is this

if (DateTime.TryParseExact(StartDate, "dd-MMM-yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dtStart))

When running through SQL Agent, it fails and produces a default time, when running through Task Scheduler or running the exe it works. Nothing has changed on my system or the way the data is being presented to the application.

Any suggestions?


Solution

  • In the comments, you've stated that the value of StartDate is "3-Nov-22". That won't work with the format string "dd-MMM-yy", which requires 2 digits for the day. Changing the format string to "d-MMM-yy" should fix your problem. For more information about date/time format strings, please see the documentation on the subject.

    As for why there is a difference in date formatting between the different ways of running the program, I would actually be very interested to see if anyone is able to shed some light on that.