千锋教育-做有情怀、有良心、有品质的职业教育机构

手机站
千锋教育

千锋学习站 | 随时随地免费学

千锋教育

扫一扫进入千锋手机站

领取全套视频
千锋教育

关注千锋学习站小程序
随时随地免费学习课程

当前位置:首页  >  技术干货  > java获取当前年月日时分秒

java获取当前年月日时分秒

来源:千锋教育
发布人:xqq
时间: 2023-08-25 03:40:49 1692906049

Java获取当前年月日时分秒的方法有多种,下面将介绍几种常用的方式。

1. 使用Java的Date类和SimpleDateFormat类:

`java

import java.util.Date;

import java.text.SimpleDateFormat;

public class GetCurrentDateTime {

public static void main(String[] args) {

// 创建Date对象

Date date = new Date();

// 创建SimpleDateFormat对象,指定日期时间格式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// 使用SimpleDateFormat对象格式化Date对象,得到当前日期时间字符串

String currentDateTime = sdf.format(date);

// 输出当前日期时间

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

}


这种方法使用了Java的Date类和SimpleDateFormat类来获取当前日期时间,并指定了日期时间的格式。通过调用SimpleDateFormat对象的format()方法,将Date对象格式化为指定格式的字符串。
2. 使用Java 8的新日期时间API(java.time包):
`java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class GetCurrentDateTime {
    public static void main(String[] args) {
        // 获取当前日期时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        
        // 创建DateTimeFormatter对象,指定日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        // 使用DateTimeFormatter对象格式化LocalDateTime对象,得到当前日期时间字符串
        String formattedDateTime = currentDateTime.format(formatter);
        
        // 输出当前日期时间
        System.out.println("当前日期时间:" + formattedDateTime);
    }

这种方法使用了Java 8引入的新日期时间API,其中LocalDateTime类表示日期时间,DateTimeFormatter类用于格式化日期时间字符串。通过调用LocalDateTime对象的format()方法,将日期时间格式化为指定格式的字符串。

3. 使用第三方库Joda-Time:

`java

import org.joda.time.DateTime;

import org.joda.time.format.DateTimeFormat;

import org.joda.time.format.DateTimeFormatter;

public class GetCurrentDateTime {

public static void main(String[] args) {

// 获取当前日期时间

DateTime currentDateTime = new DateTime();

// 创建DateTimeFormatter对象,指定日期时间格式

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

// 使用DateTimeFormatter对象格式化DateTime对象,得到当前日期时间字符串

String formattedDateTime = currentDateTime.toString(formatter);

// 输出当前日期时间

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

}

这种方法使用了Joda-Time库,它提供了更加方便和灵活的日期时间操作。通过创建DateTime对象表示当前日期时间,并使用DateTimeFormatter对象格式化DateTime对象,得到指定格式的日期时间字符串。

以上是几种常用的Java获取当前年月日时分秒的方法,你可以根据自己的需求选择适合的方法来使用。

声明:本站稿件版权均属千锋教育所有,未经许可不得擅自转载。
10年以上业内强师集结,手把手带你蜕变精英
请您保持通讯畅通,专属学习老师24小时内将与您1V1沟通
免费领取
今日已有369人领取成功
刘同学 138****2860 刚刚成功领取
王同学 131****2015 刚刚成功领取
张同学 133****4652 刚刚成功领取
李同学 135****8607 刚刚成功领取
杨同学 132****5667 刚刚成功领取
岳同学 134****6652 刚刚成功领取
梁同学 157****2950 刚刚成功领取
刘同学 189****1015 刚刚成功领取
张同学 155****4678 刚刚成功领取
邹同学 139****2907 刚刚成功领取
董同学 138****2867 刚刚成功领取
周同学 136****3602 刚刚成功领取
相关推荐HOT