From 204514cb08cbf6e6171d603e7c09a6bae249371a Mon Sep 17 00:00:00 2001 From: Redkale <8730487+redkale@users.noreply.github.com> Date: Fri, 18 Jan 2019 10:41:30 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0Utility.nowMillis=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/org/redkale/util/Utility.java | 57 ++++++++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/src/org/redkale/util/Utility.java b/src/org/redkale/util/Utility.java index 453f1b91f..495370c6a 100644 --- a/src/org/redkale/util/Utility.java +++ b/src/org/redkale/util/Utility.java @@ -31,8 +31,8 @@ public final class Utility { private static final int zoneRawOffset = TimeZone.getDefault().getRawOffset(); - private static final String format = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS"; - + //static final String format = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS"; + //static final String format = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL"; private static final char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; /** @@ -884,7 +884,16 @@ public final class Utility { * @return 格式为yyyy-MM-dd HH:mm:ss的时间值 */ public static String now() { - return String.format(format, System.currentTimeMillis()); + return formatTime(19, -1); + } + + /** + * 获取格式为yyyy-MM-dd HH:mm:ss.fff的当前时间 + * + * @return 格式为yyyy-MM-dd HH:mm:ss.fff的时间值 + */ + public static String nowMillis() { + return formatTime(23, -1); } /** @@ -895,7 +904,47 @@ public final class Utility { * @return 格式为yyyy-MM-dd HH:mm:ss的时间值 */ public static String formatTime(long time) { - return String.format(format, time); + return formatTime(19, time); + } + + /** + * 将指定时间格式化为 yyyy-MM-dd HH:mm:ss + * + * @param time 待格式化的时间 + * + * @return 格式为yyyy-MM-dd HH:mm:ss的时间值 + */ + private static String formatTime(int length, long time) { + Calendar cal = Calendar.getInstance(); + if (time > -1) cal.setTimeInMillis(time); + StringBuilder sb = new StringBuilder(length); + int month = cal.get(Calendar.MONTH) + 1; + int day = cal.get(Calendar.DAY_OF_MONTH); + int hour = cal.get(Calendar.HOUR_OF_DAY); + int minute = cal.get(Calendar.MINUTE); + int seconds = cal.get(Calendar.SECOND); + sb.append(cal.get(Calendar.YEAR)).append('-'); + if (month < 10) sb.append('0'); + sb.append(month).append('-'); + if (day < 10) sb.append('0'); + sb.append(day).append(' '); + if (hour < 10) sb.append('0'); + sb.append(hour).append(':'); + if (minute < 10) sb.append('0'); + sb.append(minute).append(':'); + if (seconds < 10) sb.append('0'); + sb.append(seconds); + if (length > 20) { + int millis = cal.get(Calendar.MILLISECOND); + sb.append('.'); + if (millis < 10) { + sb.append("00"); + } else if (millis < 100) { + sb.append('0'); + } + sb.append(millis); + } + return sb.toString(); } /**