JavaNoob
JavaNoob

Reputation: 3632

C# How to convert String into Time and Date format?

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

However it seems that the String is not recorgnizable for the system to be converted into date time format due to the sequence of the string. The String that should be converted is an example like : "Thu Dec 9 05:12:42 2010"

The method of Convert.ToDateTime have been used but does not work.

May someone please advise on the codes? Thanks!

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"));

Upvotes: 3

Views: 4504

Answers (5)

Geoff Appleford
Geoff Appleford

Reputation: 18832

Take a look at 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);
}

Upvotes: 6

Longstream
Longstream

Reputation: 21

Not sure if the string input should have the double space but you could pull that out and use geoff's answer.

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

Other option is to adjust his match string accordingly.

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

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064004

It is often necessary to give it a hint about the specific pattern that you expect:

Edit: the double-space is a pain, as d doesn't handle that;

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

Upvotes: 1

Yanshof
Yanshof

Reputation: 9926

Try this

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

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

Upvotes: 0

Nicolas Repiquet
Nicolas Repiquet

Reputation: 9265

Take a look at DateTime.Parse

Upvotes: 0

Related Questions