Date,Calendar,SimpleDateFormat都不是线程安全的
如果是 JDK8 的应用,可以使用 Instant 代替 Date,LocalDateTime 代替 Calendar, DateTimeFormatter 代替 SimpleDateFormat,官方给出的解释:simple beautiful strong immutable thread-safe
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class App {
public static void main(String[] args) throws Exception {
//获取当前时间
LocalDateTime currentTime=LocalDateTime.now();
System.out.println(currentTime);
//获取月份
System.out.println(currentTime.getMonthValue());
//获取星期几
System.out.println(currentTime.getDayOfWeek().getValue());
//格式化时间
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(dateTimeFormatter.format(currentTime));
}
}