如何在 struts2 中转换非 SHORT 格式的日期? [英] How do I convert dates in struts2 that aren't in SHORT format?

查看:29
本文介绍了如何在 struts2 中转换非 SHORT 格式的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 struts2 可以在填充我的控制器的字段时将字符串转换为日期,但是,它这样做是假设日期字符串为 SHORT 格式.有没有办法为 struts 指定不同的格式(例如,'yyyy-MM-dd')?

I know that struts2 can convert strings to Dates when populating the fields of my controller, however, it does so assuming the date string is in SHORT format. Is there a way to specify a different format for struts to use (for example, 'yyyy-MM-dd')?

推荐答案

您需要创建自己的 CustomType 转换器,它可以将给定的日期更改为任何格式.类似的东西

You need to create your own CustomType converter which can change the given date to any format. Something like

public class MyDateConvertor extends StrutsTypeConverter {
     public Object convertFromString(Map context, String[] values, Class 
toClass) {
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
          try {
              Date date = (Date) sdf.parse(values[0]);
              return new java.sql.Date(date.getTime()) ;
          } catch (ParseException e) {
              return values[0];
          }
      }

      public String convertToString(Map context, Object o) {
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         return sdf.format(o);
      }
  }

您可以从 Struts2 官方文档中获取更多详细信息,这里是详细信息

You can get more details form Struts2 official documents and here are the details

Struts2 自定义类型转换

这篇关于如何在 struts2 中转换非 SHORT 格式的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆