質問

I have been trying to get a date conversion to wrok to convert from a string to a date I have looked at msdn and some other stack o questions but multiple ways have not worked. I am making a console app and it needs a valid date to check other dates. below is my current attempt.

string StartDate, EndDate;
Console.WriteLine("Input Start date");
StartDate = Console.ReadLine();
StartDate = DateTime.Parse(StartDate);

I currently set the variable StartDate and then set it a value depending on what the user enters and then it should change this to a date using the Parse

役に立ちましたか?

解決 2

A string is not a DateTime and a DateTime not a String. So you might be able to parse a string to a date but you cannot use the string variable for the DateTime and vice-versa. You need two variables:

string startDateInput = Console.ReadLine();
DateTime startDate = DateTime.Parse( startDateInput );

Since this could fail if the input string is not a valid date you should use TryParse:

DateTime startDate;
bool validDate = DateTime.TryParse(startDateInput, out startDate);
if(validDate)
    Console.Write("Valid date: " + startDate.ToLongDateString());

他のヒント

you are trying to assign the DateTime value to string StartDate, which is wrong. So change it like below:

string StartDate, EndDate;
DateTime date;       
Console.WriteLine("Input Start date");
StartDate = Console.ReadLine();
date = DateTime.Parse(StartDate);

Try using Convert.ToDateTime();

Example:

string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);

Use DateTime.TryParse()

Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

DateTime date;

if (!DateTime.TryParse("DateString", out date))
   {
      MessageBox.Show("Invalid string!");
   }

You need to specify the Date Format.

Try This: Example format MM-dd-yyyy

Console.WriteLine("Input Start date Format -> MM-dd-yyyy");
string StartDate = Console.ReadLine();
DateTime YourDate = DateTime.ParseExact(StartDate,"MM-dd-yyyy", 
                    System.Globalization.CultureInfo.InvariantCulture);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top