6/21/12

Localized type conversion

If you need a DateTime or double convertion depending on system localization here are some examples:
Date to string
DateTime dt = new DateTime(2012, 06, 13, 17, 50, 00);

string date_US = dt.ToString(new CultureInfo("en-US").DateTimeFormat);

string date_GB = dt.ToString(new CultureInfo("en-GB").DateTimeFormat);

string date_PL = dt.ToString(new CultureInfo("pl-PL").DateTimeFormat);

string date_RU = dt.ToString(new CultureInfo("ru-RU").DateTimeFormat);

Console.WriteLine("date_US = {0}", date_US);
Console.WriteLine("date_GB = {0}", date_GB);
Console.WriteLine("date_PL = {0}", date_PL);
Console.WriteLine("date_RU = {0}", date_RU);

/*
date_US = 6/13/2012 5:50:00 PM
date_GB = 13/06/2012 17:50:00
date_PL = 2012-06-13 17:50:00
date_RU = 13.06.2012 17:50:00
*/
String to date
date_US = "6/13/2012 5:50:00 PM";
date_GB = "13/06/2012 17:50:00";
date_PL = "2012-06-13 17:50:00";
date_RU = "13.06.2012 17:50:00";

DateTime dt_US = Convert.ToDateTime(date_US, new CultureInfo("en-US").DateTimeFormat);

DateTime dt_GB = Convert.ToDateTime(date_GB, new CultureInfo("en-GB").DateTimeFormat);

DateTime dt_PL = Convert.ToDateTime(date_PL, new CultureInfo("pl-PL").DateTimeFormat);

DateTime dt_RU = Convert.ToDateTime(date_RU, new CultureInfo("ru-RU").DateTimeFormat);

Console.WriteLine("Dates Compre {0}", DateTime.Compare(dt_US, dt_GB));
Console.WriteLine("Dates Compre {0}", DateTime.Compare(dt_GB, dt_PL));
Console.WriteLine("Dates Compre {0}", DateTime.Compare(dt_PL, dt_RU));

/*
Dates Compre 0
Dates Compre 0
Dates Compre 0
*/
Double to string and string to double
double d = 1003.045;
string double_US = Convert.ToString(d, new CultureInfo("en-US").NumberFormat);
string double_PL = Convert.ToString(d, new CultureInfo("pl-PL").NumberFormat);

Console.WriteLine("double_US = {0}", double_US);
Console.WriteLine("double_PL = {0}", double_PL);
/*
double_US = 1003.045
double_PL = 1003,045
*/

double_US = "1003.045";
double_PL = "1003,045";


double d_US = Convert.ToDouble(double_US, new CultureInfo("en-US").NumberFormat);
double d_PL = Convert.ToDouble(double_PL, new CultureInfo("pl-PL").NumberFormat);

Console.WriteLine("Double compare {0}", d_US == d_PL);
/*
Double compare True
*/

1 comment:

  1. To use a neutral CI use:
    System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("");

    ReplyDelete