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
714 views
in Technique[技术] by (71.8m points)

c# - string represents date, and reformat it

The following case: There is a string that has this format "2012-02-25 07:53:04"

But in the end, i rather want to end up with this format "25-02-2012 07:53:04"

I think i have 2 options. 1 would be to reformat the string and move it all around, but i dont think this is a clean way of doing this.

A other way that i was thinking about is to save the source string to a date parameter, and then write the date parameter back to a string in a certain date format. But is this even possible to do ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Do this:

DateTime.Parse("2012-02-25 07:53:04").ToString("dd-MM-yyyy hh:mm:ss");

Keep in mind this isn't culture-aware. And if you do need to store the intermediate result you could do that just as easily:

var myDate = DateTime.Parse("2012-02-25 07:53:04");
var myDateFormatted = myDate.ToString("dd-MM-yyyy hh:mm:ss");

Lastly, check out TryParse() if you can't guarantee the input format will always be valid.


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

...