PT
Java - como formatar a data atual com o padrão de milissegundos, por exemplo: yyyy-MM-dd HH: mm: ss.milliseconds
3 points
Em java, podemos exibir a hora atual com o padrão de milissegundos quando usamos o padrão SSS
.
Ex.:
xxxxxxxxxx
1
yyyy-MM-dd HH:mm:ss.SSS
xxxxxxxxxx
1
import java.time.LocalDateTime;
2
import java.time.format.DateTimeFormatter;
3
4
public class Example1 {
5
6
public static void main(String[] args) {
7
8
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
9
LocalDateTime localDateTime = LocalDateTime.now();
10
11
String format = fmt.format(localDateTime);
12
System.out.println(format); // 2019-10-13 12:56:53.220
13
}
14
}
Resultado:
xxxxxxxxxx
1
2019-10-13 12:56:53.220
xxxxxxxxxx
1
import java.time.ZonedDateTime;
2
import java.time.format.DateTimeFormatter;
3
4
public class Example2 {
5
6
public static void main(String[] args) {
7
8
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS Z");
9
ZonedDateTime zonedDateTime = ZonedDateTime.now();
10
11
String format = fmt.format(zonedDateTime);
12
System.out.println(format); // 2019-10-13 13:07:10.912 +0200
13
}
14
}
Resultado:
xxxxxxxxxx
1
2019-10-13 13:07:10.912 +0200
xxxxxxxxxx
1
import java.text.SimpleDateFormat;
2
import java.util.Date;
3
4
public class Example3 {
5
6
public static void main(String[] args) {
7
8
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
9
Date date = new Date();
10
11
String format = fmt.format(date);
12
System.out.println(format); // 2019-10-13 12:57:05.053
13
}
14
}
Resultado:
xxxxxxxxxx
1
2019-10-13 12:57:05.053
xxxxxxxxxx
1
import java.text.SimpleDateFormat;
2
import java.util.Calendar;
3
4
public class Example4 {
5
6
public static void main(String[] args) {
7
8
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
9
Calendar calendar = Calendar.getInstance();
10
11
String format = fmt.format(calendar.getTime());
12
System.out.println(format); // 2019-10-13 12:57:14.897
13
}
14
}
Resultado:
xxxxxxxxxx
1
2019-10-13 12:57:14.897