Date Tool Example

This Example shows you how to display date and time velocity.

Date Tool Example

Date Tool Example

     

This Example shows you how to display date and time velocity. The methods used in this example are described below:- 

1:- Initialize velocity run time engine through method  init().
2:- Create object of VelocityContext Class.
3:- Create Template class object, Template  class object is used for controlling template methods and properties.

template.merge(context, writer): Merge method of the Template class is used here for merging  the VelocityContext class objects to produce the output. Template class object is used for controlling template methods and properties.

Date date = cal.getTime(): Here we created Date class object by using Calender class object.

$date.getHours(), $date.getMinutes(), $date.getSeconds(): getHours() is used here to print hours, getMinutes() is used here to print minutes, getSeconds() is used here to print seconds.

$date.getDate(), $date.getMonth(), $date.getYear(): getDate() is used here to print  date, getMonth() is used here to print month, getYear() is used here to print year.

 

DateToolClass.java

package velocity.dateTool;

import java.io.*;
import java.util.*;
import org.apache.velocity.*;
import org.apache.velocity.app.*;

public class DateToolClass {

  public static void main(String[] argsthrows Exception {
  Velocity.init();

  Template template = 
Velocity.getTemplate
("./src/velocity/dateTool/dateTool.vm");

  VelocityContext context = new VelocityContext();

  Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("PST"));

  Date date = cal.getTime();
  context.put("date", date);
  

  Writer writer = new StringWriter();
  template.merge(context, writer);

  System.out.println(writer);
  }
}

Product.vm

$date;

Time  $date.getHours():$date.getMinutes():$date.getSeconds()
Date  $date.getDate()/$date.getMonth()/$date.getYear()

Output:

Fri Aug 22 17:15:15 IST 2008;

Time  17:15:15
Date  22/7/108

Download code