Using non-core EXSLT date functions with Xalan Java

前端 未结 2 1638
感情败类
感情败类 2021-01-28 17:07

I have had EXSLT\'s core date functions working well in some XSL templates I\'ve been using for years. I\'d like to start using a new one: seconds. This function is

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-28 17:47

    For those who want to roll their own (for seconds() specifically), it can be done rather simply using this code:

    package tools;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.text.ParseException;
    
    public class Dates
    {
      /**
       * Converts a date in xs:dateTime format into seconds-since-the-epoch
       * 
       * @param date The date to be converted,
       *             in s:dateTime format (yyyy-MM-dd'T'hh:mm:ss).
       *
       * @return Number of seconds since 1970-01-01 00:00:00,
       *         or 0 if the date is blank or null.
       * @throws ParseException
       */
      public static long seconds(String date)
          throws ParseException
      {
          if(null == date || 0 == date.trim().length()) return 0;
    
          SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
          Date d = df.parse(date);
    
          return d.getTime() / 1000;
      }
    }
    

    This can be used through Apache Xalan like this:

    
    
    

    I'll probably look at the Xalan source in order to make this more flexible, but for now it seems to be doing what I'd like it to do.

提交回复
热议问题