开发者

String to DateTime conversion as per specified format

I would like to have my end result in date format开发者_JAVA技巧 as per the specified format i.e YYMMDD how can i get this from a string given as below

   string s="110326";  


From string to date:

DateTime d = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);

Or the other way around:

string s = d.ToString("yyMMdd");

Also see this article: Custom Date and Time Format Strings


DateTime dateTime = DateTime.ParseExact(s, "yyMMdd", CultureInfo.InvariantCulture);

although id recommend

DateTime dateTime;
if (DateTime.TryParseExact(s, "yyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dateTime))
{
    // Process
}
else
{
    // Handle Invalid Date
}


To convert DateTime to some format, you could do,

 string str = DateTime.Now.ToString("yyMMdd");

To convert string Date in some format to DateTime object, you could do

DateTime dt = DateTime.ParseExact(str, "yyMMdd", null);  //Let str="110719"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜