1 13 package info.magnolia.cms.util; 14 15 import info.magnolia.context.MgnlContext; 16 17 import java.text.DateFormat ; 18 import java.text.ParseException ; 19 import java.text.SimpleDateFormat ; 20 import java.util.Calendar ; 21 import java.util.Date ; 22 import java.util.TimeZone ; 23 24 import org.apache.commons.lang.time.DateFormatUtils; 25 import org.apache.commons.lang.time.FastDateFormat; 26 27 28 32 public class DateUtil { 33 34 37 public static final String FORMAT_DEFAULTPATTERN = "yyyy-MM-dd'T'HH:mm:ss.SZ"; 39 public static final String YYYY_MM_DD = "yyyy-MM-dd"; 40 41 public static final String YYYY_MM_DD_T_HH_MM_SS = "yyyy-MM-dd' 'HH:mm:ss"; 42 43 public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC"); 44 45 public String getFormattedDate(Date date) { 46 return this.getFormattedDate(date, FORMAT_DEFAULTPATTERN); 47 } 48 49 public String getFormattedDate(Date date, String formatPattern) { 50 if (formatPattern == null) { 51 formatPattern = FORMAT_DEFAULTPATTERN; 52 } 53 return DateFormatUtils.formatUTC(date, formatPattern); 54 } 55 56 61 public static String formatDateTime(Object val) { 62 FastDateFormat format = FastDateFormat.getDateTimeInstance( 63 FastDateFormat.SHORT, 64 FastDateFormat.SHORT, 65 MgnlContext.getLocale()); 66 return format.format(val); 67 } 68 69 74 public static String formatDate(Object val) { 75 FastDateFormat format = FastDateFormat.getDateInstance( 76 FastDateFormat.SHORT, 77 MgnlContext.getLocale()); 78 return format.format(val); 79 } 80 81 87 public static Date parseDateTime(String dateStr) throws ParseException { 88 DateFormat format = SimpleDateFormat.getDateTimeInstance( 89 FastDateFormat.SHORT, 90 FastDateFormat.SHORT, 91 MgnlContext.getLocale()); 92 return (Date )format.parseObject(dateStr); 93 } 94 95 101 public static Date parseDate(String dateStr) throws ParseException { 102 DateFormat format = SimpleDateFormat.getDateInstance( 103 FastDateFormat.SHORT, 104 MgnlContext.getLocale()); 105 return format.parse(dateStr); 106 } 107 108 111 public static Calendar getLocalCalendarFromUTC(Calendar utc) { 112 Date valueDate = utc.getTime(); 113 Calendar c = Calendar.getInstance(); c.setTime(valueDate); 115 return c; 116 } 117 118 121 public static Calendar getUTCCalendarFromDialogString(String dateString) throws ParseException { 122 SimpleDateFormat sdf = (dateString.length() > YYYY_MM_DD.length()) 123 ? new SimpleDateFormat (YYYY_MM_DD_T_HH_MM_SS) 124 : new SimpleDateFormat (YYYY_MM_DD); 125 return getUTCCalendarFromLocalDate(sdf.parse(dateString)); 126 } 127 128 131 public static Calendar getUTCCalendarFromLocalDate(Date date) { 132 Calendar instance = getCurrentUTCCalendar(); 133 instance.setTimeInMillis(date.getTime()); 134 return instance; 135 } 136 137 140 public static Calendar getCurrentUTCCalendar() { 141 return Calendar.getInstance(UTC_TIME_ZONE); 142 } 143 } 144 | Popular Tags |