2013-03-14 61 views

回答

2
// this is your original string 
string _str = "20130101"; 

// you need to convert it to valid DateTime datatype 
// so you can freely format the string to what you want 
DateTime _date = DateTime.ParseExact(_str, "yyyyMMdd", CultureInfo.InvariantCulture); 

// converting to your desired format, which is now a string 
string _dateStr = _date.ToString("yyyy-MM-dd"); 
2

你必須解析DateTime,然後重新格式化:

var input = ... 
var inFormat = "yyyyMMdd"; 
var outFormat = "yyyy-MM-dd"; 
var date = DateTime.ParseExact(inFormat, input, CultureInfo.InvariantCulture); 
var output = date.ToString(outFormat); 
1

安全的方法是將其轉換爲DateTime對象,例如在.net使用以下功能:

DateTime.TryParseExact() 

,然後使用DateTime對象可以重新格式化。像下面的例子:

dateTimeObject.ToString(YourFormatInString); 

檢查MSDN瞭解更多詳情:http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx