簡體   English   中英

將日期時間轉換為字符串

[英]converting date time to string

我有一個字符串變量st ,我已使用此語句分配了此字符串變量以輸出即將到來的表單數據表

string st;

if(dt!=null)
{
    if(dt.rows.count> 0)
    {
        st = dt.Rows[3]["timeslot_StartTime"].ToString();
    }
}

現在我想將此字符串變量轉換為日期時間屬性,我已經通過使用以下語句完成了此操作

DateTime pt1 = DateTime.Parse(st);

但是它在st表示use of unassigned local varaible "st"時顯示錯誤。

st初始化為null或string.Empty

string st = null;

為了安全起見,請在解析前檢查st是否為null。

st一個初始值,例如

string st = String.Empty;

嘗試以這種方式定義st

string st = "" 

嘗試做到這一點

string st = null;

解析前檢查st是否為null

可能您正在使用的變量與分配變量的范圍不同,例如

string st;
if (condition) {
    st = dt.Rows[3]["timeslot_StartTime"].ToString();
}
DateTime pt1 = DateTime.Parse(st);

因此, st並不總是被初始化(僅當if條件被驗證時)。 試試吧

string st;
if (condition) {
    st = dt.Rows[3]["timeslot_StartTime"].ToString();
    DateTime pt1 = DateTime.Parse(st);
}

您只能在if邏輯內分配st 如果嘗試在這些塊之外使用st ,則會遇到“ unssignment”錯誤。

要么

  • 初始化變量時給它一個默認值
    • 可以解析的內容,或者在嘗試解析之前記得包括檢查
  • 或嘗試從數據表中檢索值時將其解析為DateTime

當然,假設您要從DataTable中提取該值,如果該值已作為日期存儲在表中 ,則請忘記ToString()並完全解析。

DateTime date = (DateTime)dt.Rows[x]["ColumnName"];

您需要初始化字符串。 現在,任何初始化或賦值都在if塊內執行。 編譯器正在檢測到此情況,並考慮可能從未初始化過。

string st = string.Empty;

附帶說明一下,使用姐妹方法TryParse()進行對話要安全得多,以確保不會因格式問題而引發任何意外異常。 如果轉換成功,該方法將返回true,其外觀如下所示:

        if (dt!=null)
        {
           if(dt.rows.count> 0)
           {
              st = dt.Rows[3]["timeslot_StartTime"].ToString();
           }
        }

        DateTime dt = DateTime.MinValue;
        if (DateTime.TryParse(st, out dt))
        {
            //was successful and do something here
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM