Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string interpolation with CultureInfo?

Tags:

c#

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.

like image 534
Snorre Avatar asked Apr 14 '19 11:04

Snorre


People also ask

How do you use string interpolation?

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}?\

How do you use string interpolation in darts?

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.

Why do we use string interpolation?

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.

How do you use curly braces in string format?

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.


2 Answers

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}")
like image 129
Rm558 Avatar answered Nov 14 '22 22:11

Rm558


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 .

like image 28
Tor Håkon Holthe Avatar answered Nov 14 '22 21:11

Tor Håkon Holthe