java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > 获取当前时间方式(String形式)

获取当前时间方式(String形式)一行代码搞定

作者:懒鱼七忆

文章指出部分公司用varchar存储时间以避免转换,但传统方法需三行代码,建议使用一行代码通过LocalDateTime.now()和DateTimeFormatter直接输出格式化时间字符串(如"yyyy-MM-ddHH:mm:ss"),简化开发流程

获取当前时间方式(String形式)

有的公司,存储数据库的时间格式不是datetime而是直接用的varchar,这样方便取的时候避免时间转换,但是如果要存当前时间,一般都是至少三行搞定。

    // 创建日期对象
    Date now = new Date();

    // 创建日期格式化对象
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 格式化日期对象为字符串
    String currentTime = format.format(now);

    // 输出当前时间字符串
    System.out.println("当前时间:" + currentTime);

然后,为了减少代码量(秉着能少写就少写的原则,一行代码就行)

package Lx;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TimeString {
	 public static void main(String[] args) {
		    String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
		    System.out.println("当前时间:" + currentTime);
		  }
}

打印结果

这行代码使用LocalDateTime.now()获取当前时间,并使用DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")指定日期格式。

然后通过format()方法将LocalDateTime对象转换为字符串表示。

输出的结果将是格式为"yyyy-MM-dd HH:mm:ss"的当前时间字符串,

例如:

“2023-11-01 10:07:38”。你可以根据需要修改日期格式的模式。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文