Formatting Date in C #

I have a string used to display datetime, e.g. Mon, dd Dec YYYY hh: mm: ss. I want to show it as dd Dec YYYY. Is there an easy way to do this?

+4
source share
6 answers

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" AM or PM 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 a string, just split the string into an array and concatenate the parts you want in a different order

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

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

+2
source

You can call 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 parameters for format strings.

+3
source
 DateTime myDateTime = DateTime.Parse(myStringContainingDate); myDateTime.ToString("dd MMM yyyy") 

Gotta do the trick

+2
source

You can simply use a substring, as it will always be 11 characters starting at position 5.

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

Full specification here .

0
source

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

I believe the correct line would be dd MMM yyyy

0
source

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


All Articles