How to get the Previous date from the Input in C#

Viewed 27

My Code is as follows:

String DateTime = "20221002" (Format =  "yyyyMMdd" )

Expected Result:

"20220930" ( Same format as above )

Code written:

public string FormatDateTime(string param1)
{
   return Convert.ToDateTime(param1).AddDays(-1).ToString();
}

Exception Detail :

System.FormatException was unhandled
  HResult=-2146233033
  Message=String was not recognized as a valid DateTime.
  Source=mscorlib
  StackTrace:
       at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
       at System.Convert.ToDateTime(String value)
       at ConsoleApplication1.Program.Main(String[] args) in C:\Users\adharmalin\Documents\Visual Studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 235
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

Am I missing something? I am getting a syntax error.

1 Answers

You can use ParseExact (or the TryParseExact if you're not sure it's valid)

public string FormatDateTime(string param1)
        {
            var myDate = DateTime.ParseExact(param1, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
            
            return myDate.AddDays(-1).ToString();
        }

        [TestMethod]
        public void TestDate()
        {
            String DateTime = "20221002";
            Console.WriteLine(FormatDateTime(DateTime));

        }
Related