简体   繁体   中英

How to format a string containing numbers and characters

I have the following string "2017-2" and I need to format it as "2017-02" .

var period = "2017-2";
var periodFormatted = String.Format("{0:0000-00}", period);  

periodFormatted returns "2017-2"

What is the correct syntax to get the period formatted as "2017-02" ?

string.Format won't know (or care) that your string contains numbers so you cannot directly format like that. You could split up the string and parse the last part as a number though. For example:

var period = "2017-2";
var parts = period.Split('-');;
var periodFormatted = $"{parts[0]}-{int.Parse(parts[1]):D2}";

However, you should probably have the period value as a proper DateTime object (or a custom type representing the year and month values) in the first place, that would have made the formatting trivial.

You can parse the input- string as DateTime and format it in a second step.

string period = "2017-2"; 
DateTime temp = DateTime.ParseExact(period, "yyyy-M", CultureInfo.InvariantCulture );
string result = temp.ToString("yyyy-MM");

Note: M defines the month without leading 0 and MM is always 2 digit month.

Reference: https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM