C # How to convert String to time and date format?

I have a short program that converts a string to a date and time format from a simple string.

However, it seems that String is not being reconstructed for a system that needs to be converted to a date time format due to the string sequence. The string to be converted is an example, for example: "Thu Dec 9 05:12:42 2010"

The method is used Convert.ToDateTime, but does not work.

Can someone consult on codes? Thank!

String re = "Thu Dec  9 05:12:42 2010";

DateTime time = Convert.ToDateTime(re);

Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
+3
source share
5 answers

It is often necessary to give him a hint about the specific template that you expect:

: - , d ;

DateTime time = DateTime.ParseExact(re.Replace("  "," "),
     "ddd MMM d hh:mm:ss yyyy", CultureInfo.CurrentCulture);
+1

DateTime.TryParseExact

DateTime time; 
if (DateTime.TryParseExact(re,
     "ddd MMM d hh:mm:ss yyyy", CultureInfo.CurrentCulture, 
      DateTimeStyles.None, out time)) {

    Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
} else {
    Console.WriteLine("'{0}' is not in an acceptable format.", re);
}
+6

Take a look at DateTime.Parse

0
source

try it

DateTime time = Convert.ToDateTime("2010, 9, 12, 05, 12, 42"); 

Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss")); 
0
source

Not sure if the line input should have double space, but you can extract this and use the geoff answer.

re = Regex.Replace(re, @"\s+", " ");

Another option is to customize your match string accordingly.

DateTime time = DateTime.ParseExact(re, "ddd MMM  d HH:mm:ss yyyy", CultureInfo.CurrentCulture);
0
source

Source: https://habr.com/ru/post/1779960/


All Articles