-1

I need to convert Datetime format 04-08-2021 00:00:00 to string "08/04/2021"(MM/dd/YYYY) format but when I tried this code I am getting following error

using System.IO;
using System;

class Program
{
    static void Main()
    {
        String[] Arr = new String[4];
        DateTime Date1=04-08-2021 00:00:00
        Arr[0]=Date1.ToString("MM/dd/yyyy");
        Console.WriteLine(Arr[0]);
    }
}

Error

Compilation failed: 1 error(s), 0 warnings
main.cs(10,35): error CS1525: Unexpected symbol `0'
alok sharma
  • 35
  • 1
  • 7
  • 1
    You cannot declare a datetime like that. You have to parse the string and construct the object. – fredrik Aug 10 '21 at 15:16
  • `04-08-2021 00:00:00` is unkown to C#. You either have to declare it as a string `"04-08-2021 00:00:00"` and then parse it, or declare like `new DateTime(2021,8,4)` – Magnetron Aug 10 '21 at 15:16
  • See https://stackoverflow.com/questions/21906935/how-to-initialize-a-datetime-field – Charlieface Aug 10 '21 at 15:53

1 Answers1

0

You cannot declare a DateTime as such a literal. You have to parse it as a string:

DateTime Date1 = DateTime.Parse("04-08-2021 00:00:00");
Console.WriteLine(Date1.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture));

You have to use CultureInfo.InvariantCulture to ensure that the slashes are rendered, because otherwise your current date-separators are used which might be different. For example here in germany without this i get: 08.04.2021. See the "/" custom format specifier Another way to ensure it was to escape the format specifier with ticks around:

Date1.ToString("MM'/'dd'/'yyyy")
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939