簡體   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