Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

c# - How to customize datetime format or to convert DateTime to String with required format

I have a DateTime string in 24 HOURS format .. "2009-12-31T23:59:59"
I want it in this format .. "12/31/2009 23:59:59" that is: "MM/DD/YYYY HH:MM:SS"

When I tried to covert it to string I am getting "12/31/2009 11:59:59 PM" .. though I can write a code for string manipulation .. it doesn't seem to be the efficient one .. Moreover the case become worst when I have dateTime value like "2009-1-1T1:19:15" .. here, as the string length is varying, I can't even trace the value of Hours and months using substring() and convert.ToInt() ..

I am using visual studio 2005, It is throwing error saying "Cannot implicitly convert DateTime to String" when I write this statement: ..

result = Convert.ToString(dateValue);

I simplify my question: Is there any method to convert "yyyy-mm-ddThh:mm:ss" format to "mm/dd/yyyy hh:mm:ss" .. And it must work in visual studio 2005 ..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use ParseExact to get it back to datetime:

string FormatDateTime(string dateString) {
    DateTime dt = DateTime.ParseExact(dateString, "yyyy-MM-ddTHH:mm:ss", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None);
    return dt.ToString("MM/dd/yyyy HH:mm:ss");
}

That should give you the desired output you are looking for. By using InvariantInfo, it will make sure you system settings don't replace the slashes with whatever you have currently defined in the system. I think I saw in the comments that you had a "." being used as your date separator.

http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.dateseparator.aspx http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.invariantinfo.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...