java如何将当前时间转化为yyyy-MM-dd HH:mm:ss格式呢?
下文笔者讲述将当前时间转换为yyyy-MM-dd HH:mm:ss格式的方法分享,如下所示
实现思路:
方式1:
借助SimpleDateFormat类对当前时间进行相应的转化
注意此种方式线程不安全
方式2:
借助LocalDateTime类对日期进行转换
例:
//方式1:线程不安全
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
Date now = new Date();
String time = sdf.format(now);
//方式2:(线程安全,建议使用)
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class testMain {
public static void main(String[] args) {
// yyyy-MM-dd HH:mm:ss.SSS ---> 年-月-日 时-分-秒-毫秒 (想删掉哪个小部分就直接删掉哪个小部分)
String timeStr1=LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String timeStr2=LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println("当前时间为:"+timeStr1);
System.out.println("当前时间为:"+timeStr2);
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


