1 16 17 package org.springframework.web.servlet.view.xslt; 18 19 import java.text.DateFormat ; 20 import java.text.NumberFormat ; 21 import java.text.SimpleDateFormat ; 22 import java.util.Date ; 23 import java.util.Locale ; 24 25 import javax.xml.parsers.DocumentBuilderFactory ; 26 27 import org.springframework.core.NestedRuntimeException; 28 import org.w3c.dom.Document ; 29 import org.w3c.dom.Element ; 30 import org.w3c.dom.Node ; 31 32 44 public class FormatHelper { 45 46 59 public static Node dateTimeElement(long time, String language, String country) { 60 Locale locale = getLocale(language, country); 61 return dateTimeElement(time, locale); 62 } 63 64 71 public static Node dateTimeElement(long time) { 72 return dateTimeElement(time, Locale.getDefault()); 73 } 74 75 83 public static Node dateTimeElement(long time, Locale locale) { 84 try { 85 Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); 86 Element dateNode = doc.createElement("formatted-date"); 87 88 SimpleDateFormat df = (SimpleDateFormat ) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); 90 91 Date d = new Date (time); 92 df.applyPattern("MMMM"); 93 addChild(dateNode, "month", df.format(d)); 94 df.applyPattern("EEEE"); 95 addChild(dateNode, "day-of-week", df.format(d)); 96 df.applyPattern("yyyy"); 97 addChild(dateNode, "year", df.format(d)); 98 df.applyPattern("dd"); 99 addChild(dateNode, "day-of-month", df.format(d)); 100 df.applyPattern("h"); 101 addChild(dateNode, "hours", df.format(d)); 102 df.applyPattern("mm"); 103 addChild(dateNode, "minutes", df.format(d)); 104 df.applyPattern("a"); 105 addChild(dateNode, "am-pm", df.format(d)); 106 return dateNode; 107 } 108 catch (Exception ex) { 109 throw new XsltFormattingException("Failed to create XML date element", ex); 110 } 111 } 112 113 120 public static String currency(double amount, Locale locale) { 121 NumberFormat nf = NumberFormat.getCurrencyInstance(locale); 122 return nf.format(amount); 123 } 124 125 135 public static String currency(double amount, String language, String country) { 136 Locale locale = getLocale(language, country); 137 return currency(amount, locale); 138 } 139 140 143 private static void addChild(Node parent, String name, String text) { 144 Element child = parent.getOwnerDocument().createElement(name); 145 child.appendChild(parent.getOwnerDocument().createTextNode(text)); 146 parent.appendChild(child); 147 } 148 149 152 private static Locale getLocale(String language, String country) { 153 Locale locale = null; 154 if (language == null || country == null) { 155 locale = Locale.getDefault(); 156 } 157 else { 158 locale = new Locale (language, country); 159 } 160 return locale; 161 } 162 163 164 169 public static class XsltFormattingException extends NestedRuntimeException { 170 public XsltFormattingException(String msg, Throwable ex) { 171 super(msg, ex); 172 } 173 } 174 175 } 176 | Popular Tags |