可以使用SimpleDateFormat类来实现获取当前具体日期时间,并将其转换成字符串。以下是一个示例代码:

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTimeExample {
    public static void main(String[] args) {
        // 获取当前日期时间
        Date currentDate = new Date();

        // 定义日期时间格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 转换成字符串
        String dateTimeString = dateFormat.format(currentDate);

        System.out.println("当前日期时间:" + dateTimeString);

        // 获取年月日
        SimpleDateFormat dateOnlyFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = dateOnlyFormat.format(currentDate);
        System.out.println("年月日:" + dateString);

        // 获取时分秒
        SimpleDateFormat timeOnlyFormat = new SimpleDateFormat("HH:mm:ss");
        String timeString = timeOnlyFormat.format(currentDate);
        System.out.println("时分秒:" + timeString);
    }
}

运行以上代码,会输出类似以下内容:

当前日期时间:2022-10-01 10:30:45
年月日:2022-10-01
时分秒:10:30:45

这样就可以分别获取当前的年月日和时分秒,并将其转换成字符串

java写方法获取当前具体日期时间转换成字符串并得到年月日与时分秒

原文地址: https://www.cveoy.top/t/topic/hI88 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录