Home > Blockchain >  How to set order of DateTime components while also providing CultureInfo
How to set order of DateTime components while also providing CultureInfo

Time:09-22

I have a DateTimeOffset and want to display it like this for en-GB

23/08/2020 09:00

or for en-US:

08/23/2020 09:00

but when I do

dateTimeOffset.DateTime.ToString(new CultureInfo("en-GB"));

It gives me the following (I don't want it to show AM/PM):

23/08/2020 09:00 AM

I know I can do ToString("dd/MM/yyy HH:mm"), but then the format would be wrong for US culture

CodePudding user response:

            var date = new DateTime(2020, 8, 23, 9, 0, 0);
            var gbFmt = string.Format(new CultureInfo("en-gb"), "{0:d} {0:HH:mm}", date);
            var usFmt = string.Format(new CultureInfo("en-us"), "{0:d} {0:HH:mm}", date);
            Console.Write("gb: {0}\nus: {1}\n", gbFmt, usFmt);

            /*   gb: 23/08/2020 09:00
                 us:  8/23/2020 09:00    */
             

CodePudding user response:

I managed to do it like this, using CultureInfo.DateTimeFormat

var shortDatePattern = _culture.DateTimeFormat.ShortDatePattern;
var formatString = dateTimeOffset.ToString($"{shortDatePattern} H:mm");
  • Related