Java 时间转换的实例代码
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Created by Edward on 2016/6/30. */ public class TimeUtil { /** * 将 1467341232351 转换为 指定格式 "yyyy-MM-dd HH:mm:ss.SSS" * @param time "1467342217645" * @param pattern "yyyy-MM-dd HH:mm:ss.SSS" * @return 2016-07-01 11:03:37.645 */ public static String parseLongTime2String(String time, String pattern){ Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.valueOf(time)); return new SimpleDateFormat(pattern).format(calendar.getTime()); } /** * 将指定格式的字符串转化为long * @param time "2016-07-01 10:52:41.792" * @param pattern "yyyy-MM-dd HH:mm:ss.SSS" * @return 1467341561792 */ public static long parseString2LongTime(String time, String pattern) { Date date = null; try { date = new SimpleDateFormat(pattern).parse(time); } catch (ParseException e) { e.printStackTrace(); } return date.getTime(); } public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); System.out.println(calendar.getTimeInMillis()); System.out.println(TimeUtil.parseLongTime2String(String.valueOf(calendar.getTimeInMillis()),"yyyy-MM-dd HH:mm:ss.SSS")); System.out.println(TimeUtil.parseString2LongTime("2016-07-01 10:52:41.792","yyyy-MM-dd HH:mm:ss.SSS")); } }
以上这篇Java 时间转换的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持查字典教程网。