I'm doing some testing around formatting in c#, and want to do some string interpolation while also using US CultureInfo (System.Globalization). Without string interpolation this code gives me the correct date format:
DateTime date = new DateTime(2013, 4, 22);
CultureInfo provider = new CultureInfo("en-US");
Console.WriteLine("Choosen date is: " + date.ToString("d", provider));
This will display the date on US format: Choosen date is: 4/22/2013
How can I do this when using string interpolation? Here are one of my failed attempts, using String.Format:
CultureInfo provider = new CultureInfo("en-US");
Console.WriteLine(String.Format(provider, $"Choosen date is: {date:d}"));
This displays the date in my local format: Choosen date is: 22.04.2013
Any suggestions will be much appreciated.
As the colon (":") has special meaning in an interpolation expression item, to use a conditional operator in an interpolation expression, enclose that expression in parentheses. string name = "Horace"; int age = 34; Console. WriteLine($"He asked, \"Is your name {name}?\
String interpolation is the process of inserting variable values into placeholders in a string literal. To concatenate strings in Dart, we can utilize string interpolation. We use the ${} symbol to implement string interpolation in your code.
Introduction. The string interpolation feature is built on top of the composite formatting feature and provides a more readable and convenient syntax to include formatted expression results in a result string.
To escape curly braces and interpolate a string inside the String. format() method use triple curly braces {{{ }}} . Similarly, you can also use the c# string interpolation feature instead of String.
Use FormattableString.
Console.WriteLine(
((FormattableString)$"Choosen date is: {date:d}")
.ToString(provider)
);
Tor's answer is simpler than this, unless you have multiple variables in interpolation string. FormattableString allows do multiple formats all in one shot.
here is a C# 10's way, from aepot below.
string.Create(provider, $"Choosen date is: {date:d}")
You can just do: Console.WriteLine($"Choosen date is: {date.ToString("d", provider)}"));
Just format the date the same way as the string format inside the square brackets .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With