2011-12-15 71 views
0

字符串=「880814」現在我想顯示該字符串或者通過插入解析成日期時間 字符串日期時間C#

  • 或簡稱爲88/08/14由任一裝置

    • 「/ 「in b/w
      怎麼樣?
  • +0

    解析它不會顯示出來。 – Oded 2011-12-15 11:46:46

    +0

    我建議你看看一些在日期字符串分析的豐富[文件](http://msdn.microsoft.com/en-us/library/2h3syy57.aspx)的。 或想出了當你寫你的主題許多「提出問題」之一。 – Cylindric 2011-12-15 11:47:47

    +0

    一個簡單可行的辦法是到字符串分割成3串,然後用concatinate他們「/」 – RollerCosta 2011-12-15 11:48:41

    回答

    2

    做最簡單的事情是將/插入到字符串,如果你只是想輸出與他們的字符串:

    "880814".Insert(4, "/").Insert(2, "/") 
    

    我沒有看到解析字符串轉換爲點DateTime只是爲了再次輸出到一個字符串,除非您需要驗證字符串作爲有效日期,並可能確保您可以輕鬆地更改格式。

    4

    我猜想這應該被理解爲2位數的年,月,日...

    我建議你解析它作爲一個DateTime,然後將其轉換爲自定義格式。例如,使用DateTime.TryParseExact

    DateTime date; 
    // null means "current culture" - may or may not be appropriate 
    // Ditto the AssumeLocal value... 
    if (DateTime.TryParseExact(text, "yyMMdd", null, DateTimeStyles.AssumeLocal, 
              out date)) 
    { 
        // Note this will use the date separator of the current culture 
        string formatted = date.ToString("yy/MM/dd"); 
        // Use formatted 
    } 
    else 
    { 
        // Couldn't be parsed - handle appropriately. 
    } 
    

    不會只是手動插入斜線,否則你不會早,你可以通過解析/格式化趕上無效數據。上面的代碼也借自己更好的情況下要麼您的輸入格式輸出格式的變化 - 例如,如果你想改變爲「DD-MM-YYYY」格式,這樣做,通過字符串操作顯著變化,但通過解析和重新格式化,這只是一個非常小的變化,在代碼審查中很明顯。