Pritesh Chhunchha Pritesh Chhunchha - 2 months ago 8
C# Question

How to get year in Hong kong language (culture info : zh-hk)

I want to match the string in Hong kong language
I have month and year as below in hongkong language

二零一六年六月份 ===>June 2016
二零一五年六月份 ===>June 2015


I have use culture info (zh-HK) to get month like

enter image description here

But how to get year? Please help

Answer

Basically, you need to create a dictionary that uses the Chinese characters as the key and the corresponding numbers as the value:

var dict = new Dictionary<String, String>() {
    {"零", "0"},
    {"一", "1"},
    {"二", "2"},
    {"三", "3"},
    {"四", "4"},
    {"五", "5"},
    {"六", "6"},
    {"七", "7"},
    {"八", "8"},
    {"九", "9"},
    {"十", "1"} // this is needed for the months to work. If you know Chinese you would know what I mean
};

Then, you split the input string with the separator "年":

string[] twoParts = inputString.Split('年');

You loop through each character of the first part. Using the dictionary you created, you can easily get 2016 from "二零一六".

For the second part, check whether "份" is present at the end. If it is, substring it off. (sometimes months can be written without "份"). After that, do one more substring to get rid of the "月".

Now you use the dictionary above again to turn something like "十二" to "12"

Now you have the year and the month, just create a new instance of DateTime!

Here's the full code:

string inputString = ...;
var dict = new Dictionary<String, String>() {
    {"零", "0"},
    {"一", "1"},
    {"二", "2"},
    {"三", "3"},
    {"四", "4"},
    {"五", "5"},
    {"六", "6"},
    {"七", "7"},
    {"八", "8"},
    {"九", "9"},
    {"十", "1"} // this is needed for the months to work. If you know Chinese you would know what I mean
};

string[] twoParts = inputString.Split ('年');
StringBuilder yearBuilder = new StringBuilder ();
foreach (var character in twoParts[0]) {
    yearBuilder.Append (dict [character.ToString ()]);
}

string month = twoParts [1];
if (month [month.Length - 1] == '份') {
    month = month.Substring (0, month.Length - 1);
}
month = month.Substring (0, month.Length - 1);
StringBuilder monthBuilder = new StringBuilder ();

foreach (var character in month) {
    monthBuilder.Append (dict [character.ToString ()]);
}

var date = new DateTime (Convert.ToInt32 (yearBuilder.ToString()), Convert.ToInt32 (monthBuilder.ToString()), 1);
Console.WriteLine (date);