近期遇到数据库存的时间是18位数字,很疑惑这个时间应该如何转换,搜索和学习之后,如下是时间转换方法,希望对你有所帮助
public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final long TICKS_AT_EPOCH_NT = 116444736000000000L; private static final long TICKS_PER_MILLISECOND = 10000; // 注意要使用的时区 private static TimeZone TIME_ZONE = TimeZone.getDefault(); private static final long TICKS_AT_EPOCH = 621355968000000000L; /** * NT时间戳转换 * @param str NT时间戳 * @return String 1.空返回null,2."0"返回"0",3.返回yyyy-MM-dd HH:mm:ss格式字符串 */ public static String fromNTTimeToJdate(String str) { String zero = "0"; if (oConvertUtils.isEmpty(str)) { return null; } else if (zero.equals(str)) { return zero; } else { Calendar calendar = Calendar.getInstance(TIME_ZONE); calendar.setTimeInMillis((Long.parseLong(str) - TICKS_AT_EPOCH_NT) / TICKS_PER_MILLISECOND); calendar.setTimeInMillis(calendar.getTimeInMillis() - calendar.getTimeZone().getRawOffset()); return (new SimpleDateFormat(DATE_FORMAT)).format(calendar.getTime()); } } /** * NT时间戳转换 * @param date NT时间戳 */ public static String fromDateToNTTime(Date date) { Calendar calendar = Calendar.getInstance(TIME_ZONE); calendar.setTime(date); Long time = (calendar.getTimeInMillis() + calendar.getTimeZone().getRawOffset())*TICKS_PER_MILLISECOND + TICKS_AT_EPOCH_NT; return Long.toString(time); } /** * .net18位时间戳转换 * @param str .net18位时间戳 * @return String 1.空返回null,2."0"返回"0",3.返回yyyy-MM-dd HH:mm:ss格式字符串 */ public static String fromDnetToJdate(String str) { String zero = "0"; if (oConvertUtils.isEmpty(str)) { return null; } else if (zero.equals(str)) { return zero; } else { Calendar calendar = Calendar.getInstance(TIME_ZONE); calendar.setTimeInMillis((Long.parseLong(str)-TICKS_AT_EPOCH)/TICKS_PER_MILLISECOND); calendar.setTimeInMillis(calendar.getTimeInMillis()-calendar.getTimeZone().getRawOffset()); return (new SimpleDateFormat(DATE_FORMAT)).format(calendar.getTime()); } } public static void main(String[] args) { String ntStr = "132905074373730491"; System.out.println("NT时间戳:" + fromNTTimeToJdate(ntStr)); String dntStr = "635210495600000000"; System.out.println(".net18位时间戳转换:" + fromDnetToJdate(dntStr)); System.out.println("当前的时间戳转换:" + fromDateToNTTime(new Date())); }