简体   繁体   中英

string was not recognized as a valid datetime asp.net c#

when i got the above error i tried with datetime journeydate=datetime.parse.... but that also throws a error like a field initializer cant reference the non static field, method or property.

public class aaa
{
    public string created_date { get; set; }
    DateTime journeyDate = DateTime.ParseExact(created_date, "yyyy-MM-ddThh:mm:ss", CultureInfo.InvariantCulture); // error
}

This created_date will be retrived directly from db.. Is there any possible way to avoid the string was not recognized error?

Your date format is not even close to what you throw in there. You could have at least noticed yourself that the position of year doesn't match.

public class aaa
{
    public string created_date { get; set; }
    //This code "runs" so to say. You can't put that in a class. 
    //DateTime journeyDate = DateTime.ParseExact(created_date, "yyyy-MM-ddThh:mm:ss", CultureInfo.InvariantCulture);

    //Can't do this either, because when will it be called? "runable" code needs to be in a method.
    //for(int i = 0; i < created_date.length; i++){

    //We can however only decalre journeyDate
    private DateTime journeyDate;

    //And then use either a method or constructor to set it:

    public void InitializeJourneyDate()
    {
        journeyDate = DateTime.ParseExact(created_date, "yyyy-MM-ddThh:mm:ss", CultureInfo.InvariantCulture);
    }

    public aaa()
    {
        journeyDate = DateTime.ParseExact(created_date, "yyyy-MM-ddThh:mm:ss", CultureInfo.InvariantCulture);
    }

    //Maybe the best method is to use a property getter. This will return a diffrent datetime automatically when you change your string

    private DateTime JourneyDateProp
    {
        get
        {
            return DateTime.ParseExact(created_date, "yyyy-MM-ddThh:mm:ss", CultureInfo.InvariantCulture);
        }
    }

    public void Convert()
    {
        List<string> dateTimeStrings = new List<string>(){
            "2018-01-19T09:10:52",
            "2018-01-22T09:10:52",
            "2018-01-28T09:10:52"
        };

        List<DateTime> dateTimes = new List<DateTime>();

        foreach(string s in dateTimeStrings)
        {
            dateTimes.Add(DateTime.ParseExact(created_date, "yyyy-MM-ddThh:mm:ss", CultureInfo.InvariantCulture));
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM