Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# format DateTime without year

Is there a possibility to format a DateTime without a year and with the month in a numerical representation that's internationalized?

e.g. new DateTime(2018, 8, 10) (today)

On the one hand we have "d" for 10.08.2018 (German) or 2018/08/10 (Japanese).

On the other hand we have "M" that gives us 10. August (German) or August 10 (US English)

But what I want is 10.08. (German), 08/10 (Japanese), 8/10 (US English), 10/08 (British English)

like image 853
Dominik G Avatar asked Aug 10 '18 12:08

Dominik G


1 Answers

Maybe you could take the ShortDatePattern from DateTimeFormatInfo and strip out the yyyy?

You would have to get a little creative to remove the separator with it.

A Replace chain

.Replace(DateFormatInfo.DateSeparator+"yyyy")
.Replace("yyyy"+DateFormatInfo.DateSeparator)

A Regex might do the trick ^y+[^0-9A-Za-z]+|[^0-9A-Za-z]+y+$

  string[]  cultures = { "en-US", "ja-JP", "fr-FR" };
  DateTime date1 = new DateTime(2011, 5, 1);

  Console.WriteLine(" {0,7} {1,19} {2,10}\n", "CULTURE", "PROPERTY VALUE", "DATE");

  foreach (var culture in cultures) {
     DateTimeFormatInfo dtfi = CultureInfo.CreateSpecificCulture(culture).DateTimeFormat;
     Console.WriteLine(" {0,7} {1,19} {2,10}", culture, 
                       dtfi.ShortDatePattern, 
                       date1.ToString("d", dtfi));
  }

CULTURE      PROPERTY VALUE       
en-US            M/d/yyyy  
ja-JP          yyyy/MM/dd 
fr-FR          dd/MM/yyyy 

From :https://learn.microsoft.com/en-us/dotnet/api/system.globalization.datetimeformatinfo.shortdatepattern?view=netframework-4.7.2

like image 191
Richard Hubley Avatar answered Oct 17 '22 04:10

Richard Hubley