日期转换为英国日期格式,保留0' s

时间:2017-07-20 11:32:17

标签: c#

我希望将我的日期转换为英国日期格式。 例如,如果它是26/2/2016那么它应该转换为2016年2月26日。 如果它是2/13/2016那么它应该转换为2016年2月13日。 最终结果应为英国格式,日期和月份保留为0。

代码

string cellvalue; 
string oData = "2/13/2016"; 

if (DateTime.TryParse((string)oData, CultureInfo.CurrentUICulture, styles, out dt)) 
{ 
    cellvalue = dt.ToString("dd/MM/yyyy"); 
    Console.WriteLine(cellvalue + "go to hell"); 
} 
else 
{ 
    cellvalue = oData.ToString(); 
    Console.WriteLine(cellvalue + "go to bokaro"); 
} 

2 个答案:

答案 0 :(得分:0)

Easyyy:

CultureInfo enGB = new CultureInfo("en-GB"); 
string oData = "2/13/2016"; 
DateTime dateValue;

// Parse date with no style flags.
dateString = "13/02/2016";
DateTime.TryParseExact(oData, "g", enGB, DateTimeStyles.None, out dateValue);

答案 1 :(得分:0)

据我了解,无论输入日期字符串是dd/MM/yyyy还是MM/dd/yyyy,前者都是美国的默认格式,您希望生成日期为默认的英国格式,即dd/MM/yyyy日期。

您已经尝试过的代码已经很接近了。此外,您还需要做一件事 - 如果输入采用美国格式,请使用美国文化将其解析为DateTime,然后转换为英国。

var UKCulture = new CultureInfo("en-GB");
var USCulture = new CultureInfo("en-US");
DateTime dt;
string cellvalue; 

string oData = "13/2/2016"; 

// First try parsing to UK format
if (!DateTime.TryParse(oData, UKCulture, DateTimeStyles.None, out dt)) 
{ 
    // If fails, then try US format
    DateTime.TryParse(oData, USCulture, DateTimeStyles.None, out dt);
}

// Once you have DateTime instance, you can do anything. Parsing is over.
cellvalue = dt.ToString("dd/MM/yyyy"); 
Console.Write(cellvalue);

现在,这为13/02/20162/13/2016输入提供了13/2/2016的最终值。

相关问题