开发者

Format date in C#

开发者 https://www.devze.com 2022-12-18 12:10 出处:网络
I have a string used to display the datetime, like: Mon, dd Dec YYYY hh:mm:ss. I w开发者_开发百科ant to display it like this: dd Dec YYYY. Is there any simple way to do it?You can call the formatting

I have a string used to display the datetime, like: Mon, dd Dec YYYY hh:mm:ss.

I w开发者_开发百科ant to display it like this: dd Dec YYYY. Is there any simple way to do it?


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.


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

See also:

Custom Date and Time Format Strings - MSDN

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


DateTime myDateTime = DateTime.Parse(myStringContainingDate);

myDateTime.ToString("dd MMM yyyy")

Should do the trick


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


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

I believe the correct string would be dd MMM yyyy


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

Full spec here.


In C# 6.0 you can use string interpolation in order to display formatted dates.

DateTime fullDate = DateTime.Parse("Sat, 17 JUL 2021 02:22:22");
string date = $"{fullDate: dd MMM yyyy}";
0

精彩评论

暂无评论...
验证码 换一张
取 消