如何格式化日期时间 [英] how to format Date time
问题描述
我在字符串变量中具有任何格式的Date.
我想格式化/转换成给定的格式.
我写了以下一行....
ConvertedValue = Convert.ToDateTime(CValue.Trim()).ToString(StrWizFormat.Trim());
或
ConvertedValue = ConvertFieldDatetimeFormat(CValue.Trim(), StrWizFormat.Trim()).ToString(StrWizFormat.Trim());
I have Date in any format in a string variable .
I want to format/ convert in given format.
I have written following line....
ConvertedValue = Convert.ToDateTime(CValue.Trim()).ToString(StrWizFormat.Trim());
OR
ConvertedValue = ConvertFieldDatetimeFormat(CValue.Trim(), StrWizFormat.Trim()).ToString(StrWizFormat.Trim());
private static DateTime ConvertFieldDatetimeFormat(string DValue, string DFormat)
{
System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
dateInfo.ShortDatePattern = DFormat;
DateTime CnvDtValue;
if (DValue.Trim() != string.Empty)
{
CnvDtValue = Convert.ToDateTime(DValue.Trim(), dateInfo);
}
else
{
CnvDtValue = new DateTime();
}
return CnvDtValue;
}
但在某些情况下出现错误....
请修改我的功能....
或建议我,如果您有最佳技巧....
致以问候
Manoj
but I am getting error in some case ....
Please modify my function ....
or suggest me, if you have best trick ....
With Regards
Manoj
推荐答案
如果要转换的特定格式,请使用TryParseExact:
If you have a specific format to to convert, use TryParseExact:
DateTime dt;
string date = "31/12/2011";
if (DateTime.TryParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
}
在此链接中查看C#示例,
http://msdn.microsoft.com/zh-我们/library/system.convert.todatetime%28v=vs.71%29.aspx [
Look into the C# example in this link,
http://msdn.microsoft.com/en-us/library/system.convert.todatetime%28v=vs.71%29.aspx[^]
你好,
请参考
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx [ ^ ]
另请参阅
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx [ ^ ]
hello,
please refer
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx[^]
refer this also
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx[^]
这篇关于如何格式化日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!