繁体   English   中英

字符串未被识别为有效日期时间asp.net C#

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

当我遇到上述错误时,我尝试使用datetime tripdatedate = datetime.parse ....,但这还会引发错误,例如字段初始化程序无法引用非静态字段,方法或属性。

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

此created_date将直接从db中检索。是否有任何可能的方法来避免字符串未被识别错误?

您的日期格式甚至与您输入的日期格式不符。 您可能至少已经注意到自己年份的位置不匹配。

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));
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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