1Timestamp timestamp = new Timestamp(System.currentTimeMillis());
2//2016-11-16 06:43:19.77
3Copy
1
2 // 2021-03-24 16:48:05.591
3 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
4
5 // 2021-03-24 16:48:05.591
6 Date date = new Date();
7 Timestamp timestamp2 = new Timestamp(date.getTime());
8
9 // convert Instant to Timestamp
10 Timestamp ts = Timestamp.from(Instant.now())
11
12 // convert ZonedDateTime to Instant to Timestamp
13 Timestamp ts = Timestamp.from(ZonedDateTime.now().toInstant()));
14
15 // convert Timestamp to Instant
16 Instant instant = ts.toInstant();
17
1package com.mkyong.date;
2
3import java.sql.Timestamp;
4import java.text.SimpleDateFormat;
5import java.util.Date;
6
7public class TimeStampExample {
8
9 private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
10
11 public static void main(String[] args) {
12
13 //method 1
14 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
15 System.out.println(timestamp);
16
17 //method 2 - via Date
18 Date date = new Date();
19 System.out.println(new Timestamp(date.getTime()));
20
21 //return number of milliseconds since January 1, 1970, 00:00:00 GMT
22 System.out.println(timestamp.getTime());
23
24 //format timestamp
25 System.out.println(sdf.format(timestamp));
26
27 }
28
29}
30Copy
1
2package com.mkyong.app;
3
4import java.sql.Timestamp;
5import java.text.SimpleDateFormat;
6import java.util.Date;
7
8public class TimeStampExample {
9
10 // 2021.03.24.16.34.26
11 private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
12
13 // 2021-03-24T16:44:39.083+08:00
14 private static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
15
16 // 2021-03-24 16:48:05
17 private static final SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
18
19 public static void main(String[] args) {
20
21 // method 1
22 Timestamp timestamp = new Timestamp(System.currentTimeMillis());
23 System.out.println(timestamp); // 2021-03-24 16:34:26.666
24
25 // method 2 - via Date
26 Date date = new Date();
27 System.out.println(new Timestamp(date.getTime())); // 2021-03-24 16:34:26.666
28 // number of milliseconds since January 1, 1970, 00:00:00 GMT
29 System.out.println(timestamp.getTime()); // 1616574866666
30
31 System.out.println(sdf1.format(timestamp)); // 2021.03.24.16.34.26
32
33 System.out.println(sdf2.format(timestamp)); // 2021-03-24T16:48:05.591+08:00
34
35 System.out.println(sdf3.format(timestamp)); // 2021-03-24 16:48:05
36
37 }
38}
39