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

c# - How can I convert a date string from format X to format Y?

I have a string containing a date in some format X (e.g. 12/31/2015). How can I convert it to format Y (e.g. 2015-12-31 00:00:00)?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

C# has it's own DateTime structure. The goal is to

  1. convert your string to a DateTime and then
  2. convert your DateTime back to a string.

First, you need to get the format string for both formats X and Y. Check the following two lists:

E.g., for 12/31/2015, all of d or MM/dd/yyyy (with the en-US or invariant culture) or MM/dd/yyyy (with any locale) would be fine. For 2015-12-31 00:00:00, it would be yyyy-MM-dd HH:mm:ss.


For the first step, you can use DateTime.ParseExact (or DateTime.TryParseExact, if you want to fail gracefully if the string does not have the correct format), e.g.,

var myDateTime = DateTime.ParseExact(myInputString, "MM/dd/yyyy",
                                     CultureInfo.InvariantCulture);

For the second step, use DateTime.ToString:

var myOutputString = myDateTime.ToString("yyyy-MM-dd HH:mm:ss",
                                         CultureInfo.InvariantCulture);

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

...