Home > Mobile >  Custom format Korean date with forward-slash not working
Custom format Korean date with forward-slash not working

Time:01-19

If you run the following code: https://dotnetfiddle.net/kBqe9x

using System;
                    
public class Program
{
    public static void Main()
    {
        var date = DateTime.Now;
        Console.WriteLine(date.ToString("yyyy/MM/dd", System.Globalization.CultureInfo.GetCultureInfo("ko-KR")));
    }
}

The result will be 2022-01-18.

Why is .net replacing the forward-slash with a dash?

CodePudding user response:

The forward slash is a special character, in DateTime you have to write that like '/'

using System;
                    
public class Program
{
    public static void Main()
    {
        var date = DateTime.Now;
        Console.WriteLine(date.ToString("yyyy'/'MM'/'dd", System.Globalization.CultureInfo.GetCultureInfo("ko-KR")));
    }
}

CodePudding user response:

That's because ko-KR culture info has such a date pattern for a short date. If you take a look at the ShortDatePattern property of the CultureInfo you've created here, you'll see the following.

var cultureInfo = System.Globalization.CultureInfo.GetCultureInfo("ko-KR");
Console.WriteLine(cultureInfo.DateTimeFormat.ShortDatePattern);

This prints out: yyyy-MM-dd

Fiddle: https://dotnetfiddle.net/CRxKtQ

If you want to keep the pattern you specified in ToString method, simply remove the culture info.

  •  Tags:  
  • Related