1 10 package org.mmbase.util; 11 12 import java.util.*; 13 import java.text.*; 14 15 import org.mmbase.util.logging.Logger; 16 import org.mmbase.util.logging.Logging; 17 18 25 public class DateFormats { 26 27 private static final Logger log = Logging.getLoggerInstance(DateFormats.class); 28 29 41 public static DateFormat getInstance(String format, String timeZone, Locale locale) { 42 DateFormat df; 43 if (format.length() > 0 && format.charAt(0) == ':') { 44 log.debug("found symbolic format"); 45 if (format.charAt(1) == '.') { 46 df = DateFormat.getTimeInstance(getDateFormatStyle(format.substring(2)), locale); 47 } else if (format.indexOf('.') == -1) { 48 df = DateFormat.getDateInstance(getDateFormatStyle(format.substring(1)), locale); 49 } else { 50 int i = format.indexOf('.'); 51 df = DateFormat.getDateTimeInstance(getDateFormatStyle(format.substring(1, i)), 52 getDateFormatStyle(format.substring(i+1)), locale); 53 } 54 } else if (format.equals("e")) { 55 df = new DayOfWeekDateFormat(); 56 } else if (format.equals("RFC822") || format.equals("rfc822")) { 57 df = new SimpleDateFormat("EE, dd MMM yyyy hh:mm:ss Z", Locale.US); 58 } else { 59 df = new SimpleDateFormat(format, locale); 60 } 61 if (!( timeZone == null || timeZone.equals(""))) { 62 df.setTimeZone(TimeZone.getTimeZone(timeZone)); 63 } else { 64 df.setTimeZone(org.mmbase.util.dateparser.DateParser.defaultTimeZone); 65 } 66 return df; 67 68 } 69 70 77 private static int getDateFormatStyle(String style) { 78 if ("FULL".equals(style)) { 79 return DateFormat.FULL; 80 } else if ("LONG".equals(style)) { 81 return DateFormat.LONG; 82 } else if ("MEDIUM".equals(style)) { 83 return DateFormat.MEDIUM; 84 } else if ("SHORT".equals(style)) { 85 return DateFormat.SHORT; 86 } else { 87 throw new IllegalArgumentException ("Unknown DateFormat Style " + style); 88 } 89 } 90 91 95 96 protected static class DayOfWeekDateFormat extends DateFormat { 97 private TimeZone zone = null; 98 public Date parse(String source, ParsePosition pos) { 99 Calendar calendar = Calendar.getInstance(zone != null ? zone : org.mmbase.util.dateparser.DateParser.defaultTimeZone); 100 int day = source.charAt(0) - '0'; 101 pos.setIndex(pos.getIndex() + 1); 102 calendar.set(Calendar.DAY_OF_WEEK, day); 103 return calendar.getTime(); 104 } 105 public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) { 106 Calendar calendar = Calendar.getInstance(zone != null ? zone : org.mmbase.util.dateparser.DateParser.defaultTimeZone); 107 calendar.setTime(date); 108 toAppendTo.append(calendar.get(Calendar.DAY_OF_WEEK)); 110 return toAppendTo; 111 } 112 113 public void setTimeZone(TimeZone value) { 114 zone = value; 115 } 116 117 118 } 119 } 120 | Popular Tags |