简体   繁体   English

在 C# 中格式化日期

[英]Format date in C#

I have a string used to display the datetime like Mon, dd Dec YYYY hh:mm:ss.我有一个用于显示日期时间的字符串,例如 Mon, dd Dec YYYY hh:mm:ss。 I want to show it like dd Dec YYYY.我想像 dd Dec YYYY 一样显示它。 Is there any simple way to do it?有什么简单的方法可以做到吗?

You can call the formatting methods on the DateTime class您可以调用 DateTime 类上的格式化方法

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/来自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自定义日期和时间格式字符串 - 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如果日期可以改变,那么做 SLaks 在他的回答中发布的内容

DateTime myDateTime = DateTime.Parse(myStringContainingDate);

myDateTime.ToString("dd MMM yyyy")

Should do the trick应该做的伎俩

您可以只使用 Substring,因为它总是 11 个字符,从位置 5 开始。

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

Full spec here .完整规格在这里

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

I believe the correct string would be dd MMM yyyy我相信正确的字符串是 dd MMM yyyy

In C# 6.0 you can use string interpolation in order to display formatted dates.C# 6.0您可以使用字符串插值来显示格式化的日期。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM