DateFormat扩展帮助 [英] DateFormat extension help
问题描述
大家好,我已经在项目中添加了一个实体数据模型,并使用EDM中的datetime值填充了许多文本框.
Hi everyone, I''ve an entity data model added to my project and I''m populating a number of text-boxes with the datetime value from the EDM.
txtFinancialYearFrom.Text = Convert.ToString(company.FinancialYearFrom);
但我想尝试编写一个扩展方法,该方法采用该datetime值并将其重新格式化为MMMMd格式.这是我到目前为止的内容:
But I''d like to try to write an extension method that takes that datetime value and reformats it into MMMMd format. Here''s what I have so far:
namespace ExtensionLibrary
{
//Extension methods must be defined in a static class
public static class DateFormatExtension
{
// This is the extension method.
public static String MMMMdFormat(this DateTime date)
{
return new String(date.ToString("d MMMM"));
}
}
}
在目前,这给了我2个错误:
错误1与' string.String(char [])'的最佳重载方法匹配有一些无效的参数
错误2参数1:无法从' string'转换为到' char []'</pre>
at the minute this is giving me 2 errors:
Error 1 The best overloaded method match for 'string.String(char[])' has some invalid arguments
Error 2 Argument 1: cannot convert from 'string' to 'char[]'</pre>
Has anyone tried this before?
推荐答案
您需要做的就是删除新字符串"位:
All you need to do is remove the "new String" bit:
public static class MyExtensions
{
public static String MMMMdFormat(this DateTime date)
{
return date.ToString("d MMMM");
}
}
谢谢OriginalGriff,这就是我最后得到的结果:
thank you OriginalGriff, here''s what I have ended up with:
namespace ExtensionLibrary
{
//Extension methods must be defined in a static class
public static class ExtensionLibrary
{
//This method handles any NULLABLE Datetime fields
public static String FormatNULLDateTime(this DateTime? date)
{
if (date.HasValue)
return ((DateTime)date).ToString("dd MMMM");
else
return "";
}
//This method handles non-NULLABLE Datetime fields
public static String FormatDatetime(this DateTime date)
{
return ((DateTime)date).ToString("dd MMMM");
}
}
}
这篇关于DateFormat扩展帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!