我希望我的最终结果按照指定格式为日期格式,即
YYMMDD
,我如何从下面给出的字符串中得到它? string s="110326";
将字符串转换为日期:
DateTime d = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);
或者反过来:
string s = d.ToString("yyMMdd");
还可以参考这篇文章: 自定义日期和时间格式字符串
ParseExact
需要那个参数。我编辑了答案。InvariantCulture
的优点是始终提供相同的结果,而不受用户区域设置的影响。如果您希望结果根据用户的地区而有所不同,请改用CultureInfo.CurrentCulture
。 - SvenDateTime dateTime = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);
DateTime dateTime;
if (DateTime.TryParseExact(s, "yyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dateTime))
{
// Process
}
else
{
// Handle Invalid Date
}
要将DateTime
转换为某种格式,可以执行以下操作:
string str = DateTime.Now.ToString("yyMMdd");
要将某个格式的字符串日期转换为DateTime对象
,可以执行以下操作:
DateTime dt = DateTime.ParseExact(str, "yyMMdd", null); //Let str="110719"