1 import java.text.ParseException; 2 import java.text.SimpleDateFormat; 3 import java.util.Calendar; 4 import java.util.Date; 5 6 /** 7 * Created by Edward on 2016/6/30. 8 */ 9 public class TimeUtil { 10 11 12 /** 13 * 將 1467341232351 轉換為 指定格式 "yyyy-MM-dd HH:mm:ss.SSS" 14 * @param time "1467342217645" 15 * @param pattern "yyyy-MM-dd HH:mm:ss.SSS" 16 * @return 2016-07-01 11:03:37.645 17 */ 18 19 public static String parseLongTime2String(String time, String pattern){ 20 Calendar calendar = Calendar.getInstance(); 21 calendar.setTimeInMillis(Long.valueOf(time)); 22 return new SimpleDateFormat(pattern).format(calendar.getTime()); 23 } 24 25 26 /** 27 * 將指定格式的字符串轉化為long 28 * @param time "2016-07-01 10:52:41.792" 29 * @param pattern "yyyy-MM-dd HH:mm:ss.SSS" 30 * @return 1467341561792 31 */ 32 public static long parseString2LongTime(String time, String pattern) 33 { 34 Date date = null; 35 try { 36 date = new SimpleDateFormat(pattern).parse(time); 37 } catch (ParseException e) { 38 e.printStackTrace(); 39 } 40 return date.getTime(); 41 } 42 43 public static void main(String[] args) 44 { 45 Calendar calendar = Calendar.getInstance(); 46 47 System.out.println(calendar.getTimeInMillis()); 48 49 System.out.println(TimeUtil.parseLongTime2String(String.valueOf(calendar.getTimeInMillis()),"yyyy-MM-dd HH:mm:ss.SSS")); 50 51 System.out.println(TimeUtil.parseString2LongTime("2016-07-01 10:52:41.792","yyyy-MM-dd HH:mm:ss.SSS")); 52 53 } 54 55 }