最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
asp.net中StringTemplate自定义输出日期格式
时间:2013-01-05 编辑:简简单单 来源:一聚教程网
Use additional renderers like this实现接口的类:
代码如下 | 复制代码 |
internal class AdvancedDateTimeRenderer : IAttributeRenderer { public string ToString(object o) { return ToString(o, null); } public string ToString(object o, string formatName) { if (o == null) return null; if (string.IsNullOrEmpty(formatName)) return o.ToString(); DateTime dt = Convert.ToDateTime(o); return string.Format("{0:" + formatName + "}", dt); } } |
and then add this to your StringTemplate such as把类注册到模板组中:
代码如下 | 复制代码 |
var stg = new StringTemplateGroup("Templates", path); stg.RegisterAttributeRenderer(typeof(DateTime), new AdvancedDateTimeRenderer()); |
then in st file模板文件中的写法:
代码如下 | 复制代码 |
$YourDateVariable; format="dd/mm/yyyy"$ |
另一种方法 默认都是调用attribute.ToString()方法。如果要自定义输出格式,则需要实现IAttributeRenderer接口。下面来定义一个自定义日期格式化输出:
代码如下 | 复制代码 |
class CustomDataRenderer : IAttributeRenderer { |
使用:
代码如下 | 复制代码 |
StringTemplate st = new StringTemplate("$d$"); |
可以看到输出了前面定义的ToString(object o)方法定义的格式,那么如果需要输出多种格式,这个方法就显得力不从心了。
接下来改造CustomDataRenderer类,使它能输出多种格式:
代码如下 | 复制代码 |
使用: StringTemplate st = new StringTemplate("[$d1$] [$d2;format="CNDate"$] [$d3;format="CNTime"$]"); |
输出:[2010年04月30日 21点40分] [2010年04月30日] [21点40分]
相关文章
- C#复制数组的两种方式及效率比较解读 10-24
- ASP.NET Identity用法解析 10-24
- ASP.NET MVC使用Identity增删改查用户介绍 10-24
- C语言中atoi函数模拟实现介绍 10-18
- .Net反向代理组件Yarp用法介绍 10-10
- .NET使用YARP通过编码方式配置域名转发实现反向代理教程 10-10