遵循有用的注释,我已经完全重建了日期格式化程序。用法应该是:
- 短(一根衬里)
- 用字符串表示一次性对象(时区,格式)
- 支持有用的,可排序的ISO格式以及包装盒中的旧格式
如果您认为此代码有用,则可以在github中发布源代码和JAR。
用法
// The problem - not UTCDate.toString()"Tue Jul 03 14:54:24 IDT 2012"// ISO format, nowPrettyDate.now() "2012-07-03T11:54:24.256 UTC"// ISO format, specific datePrettyDate.toString(new Date()) "2012-07-03T11:54:24.256 UTC"// Legacy format, specific datePrettyDate.toLegacyString(new Date()) "Tue Jul 03 11:54:24 UTC 2012"// ISO, specific date and time zonePrettyDate.toString(moonLandingDate, "yyyy-MM-dd hh:mm:ss zzz", "CST") "1969-07-20 03:17:40 CDT"// Specific format and datePrettyDate.toString(moonLandingDate, "yyyy-MM-dd")"1969-07-20"// ISO, specific datePrettyDate.toString(moonLandingDate)"1969-07-20T20:17:40.234 UTC"// Legacy, specific datePrettyDate.toLegacyString(moonLandingDate)"Wed Jul 20 08:17:40 UTC 1969"
码
(此代码也是 有关Code Review
stackexchange的问题的主题)
import java.text.SimpleDateFormat;import java.util.Date;import java.util.TimeZone;public class PrettyDate { public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz"; public static String LEGACY_FORMAT = "EEE MMM dd hh:mm:ss zzz yyyy"; private static final TimeZone utc = TimeZone.getTimeZone("UTC"); private static final SimpleDateFormat legacyFormatter = new SimpleDateFormat(LEGACY_FORMAT); private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT); static { legacyFormatter.setTimeZone(utc); isoFormatter.setTimeZone(utc); } public static String now() { return PrettyDate.toString(new Date()); } public static String toString(final Date date) { return isoFormatter.format(date); } public static String toLegacyString(final Date date) { return legacyFormatter.format(date); } public static String toString(final Date date, final String format) { return toString(date, format, "UTC"); } public static String toString(final Date date, final String format, final String timezone) { final TimeZone tz = TimeZone.getTimeZone(timezone); final SimpleDateFormat formatter = new SimpleDateFormat(format); formatter.setTimeZone(tz); return formatter.format(date); }}


