前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java获取系统当前时间年月日

Java获取系统当前时间年月日

作者头像
很酷的站长
发布2023-10-02 08:32:21
7310
发布2023-10-02 08:32:21
举报
文章被收录于专栏:站长的编程笔记
Java获取系统当前时间年月日
Java获取系统当前时间年月日

在Java中使用java.util.Date类和java.time.LocalDate类来获取系统当前的时间,年份,月份和日期。

一、使用java.util.Date类获得当前日期

java.util.Date类表示特定的瞬间,精确到毫秒。下面是获取当前日期和时间的代码示例:

代码语言:javascript
复制
import java.util.Date;

public class GetCurrentDateTime {
    public static void main(String[] args) {
        // create a date object with the current date and time.
        Date date = new Date();
        
        // print the date
        System.out.println("当前日期和时间: " + date.toString());
    }
}

二、使用java.time.LocalDate获取当前年月日

使用Java 8引入的java.time包中的LocalDate类,可以很方便地获取当前日期的年份,月份和日子。以下是操作的具体代码:

代码语言:javascript
复制
import java.time.LocalDate;

public class GetCurrentDate {
    public static void main(String[] args) {
        // get the current date
        LocalDate currentDate = LocalDate.now();
        
        // get the year
        int year = currentDate.getYear();
        
        // get the month
        int month = currentDate.getMonthValue();
        
        // get the day
        int day = currentDate.getDayOfMonth();
        
        // print the current date
        System.out.println("当前年份: " + year);
        System.out.println("当前月份: " + month);
        System.out.println("当前日期: " + day);
    }
}

三、使用java.text.SimpleDateFormat格式化日期

java.text.SimpleDateFormat是一个可以以用户定义的模式格式化 Date 对象的具体类。

代码语言:javascript
复制
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatCurrentDateTime {
    public static void main(String[] args) {
        // create a date object with the current date and time.
        Date now = new Date();
        
        // create an instance of SimpleDateFormat
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        
        // format the date
        String currentDateAndTime = formatter.format(now);
        
        // print the date and time
        System.out.println("当前年月日和时间: " + currentDateAndTime);
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、使用java.util.Date类获得当前日期
  • 二、使用java.time.LocalDate获取当前年月日
  • 三、使用java.text.SimpleDateFormat格式化日期
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档