我有一个格式化为YYYYMMDD的字符串-我如何以YYYY-MM-DD格式复制?
// 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");
- DateTime.ParseExact ()
您必须解析DateTime
,然后重新格式化:
var input = ...
var inFormat = "yyyyMMdd";
var outFormat = "yyyy-MM-dd";
var date = DateTime.ParseExact(inFormat, input, CultureInfo.InvariantCulture);
var output = date.ToString(outFormat);
安全的方法是将其转换为DateTime对象,例如在。net中使用下面的函数:
DateTime.TryParseExact()
,然后使用DateTime对象,您可以再次格式化它。就像下面的例子:
dateTimeObject.ToString(YourFormatInString);
查看MSDN获取更多详细信息:http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx