Java 时间转换的实例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
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 时间转换的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。