tags:

views:

73

answers:

6
+1  Q: 

Format date in C#

Hi all

I have a string used to display the datetime like Mon, dd Dec YYYY hh:mm:ss. I want to show it like dd Dec YYYY. Is there any simple way to do it?

+1  A: 

You could just use Substring, since it's always going to be 11 characters, starting at position 5.

Rob Farley
+2  A: 

You can call the formatting methods on the DateTime class

DateTime time = DateTime.ParseExact("Mon, 28 Dec 2009 04:34:17", "ddd, dd MMM yyyy hh:mm:ss", CultureInfo.InvariantCulture);
string output = time.ToString("dd MMM yyyy", CultureInfo.InvariantCulture);

Here is a list of options for the format strings.

SLaks
A: 

from http://www.csharp-examples.net/string-format-datetime/

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

if you only have the string, just split the string to an array, and concatenate the parts you want in another order

String str = "Mon, dd Dec YYYY hh:mm:ss";
String[] strArr = str.Split(" ");
str = strArr[2] + " " + strArr[3];

If the date can change, then do what SLaks posted in his answer

sergiogx
Since there's only one parameter, you should call `DateTime.ToString`.
SLaks
He doesn't have a datetime, he has a string
PostMan
just noticed that
sergiogx
the array is not a good idea, what if the date format changes? say it becomes 2010 Jan 28?
PostMan
**Do NOT do this**. it will result in brittle code that will unexpectedly return meaningless data if the date format changes. Instead, you should parse the string into a DateTime so that you get an error instead of data corruption if the format changes.
SLaks
Is it necessary to do that even tho he doesn't state it can change?, also is splitting faster or slower than creating a new date object?
sergiogx
+1  A: 
DateTime myDateTime = DateTime.Parse(myStringContainingDate);

myDateTime.ToString("dd MMM yyyy")

Should do the trick

PostMan
A: 
DateTime d = DateTime.Parse(yourDateString);
Console.WriteLine(d.ToString("dd MMM YYYY"));

Full spec here.

fatcat1111
A: 

Check out http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

I believe the correct string would be dd MMM yyyy

Mike B