Java中獲取當天的年月日

1. 使用java.util.Date類

java.util.Date類是Java中用于表示時間的類,它可以精確到毫秒。要獲取當天的年月日,我們可以使用Date類的構(gòu)造方法創(chuàng)建一個表示當前時間的Date對象,然后調(diào)用getYear()、getMonth()和getDate()方法分別獲取年、月和日。

示例代碼:

import java.util.Date;
public class GetCurrentDate {
    public static void main(String[] args) {
        // 創(chuàng)建一個表示當前時間的Date對象
        Date currentDate = new Date();
        
        // 獲取年、月和日
        int year = currentDate.getYear();
        int month = currentDate.getMonth() + 1; // 月份從0開始,所以需要加1
        int day = currentDate.getDate();
        
        // 輸出結(jié)果
        System.out.println("今天的日期是:" + year + "年" + month + "月" + day + "日");
    }
}

2. 使用java.time.LocalDate類(Java8及以上版本)

java.time包提供了更加現(xiàn)代和易用的日期時間API,其中LocalDate類專門用于表示不帶時分秒的日期。要獲取當天的年月日,我們可以使用LocalDate類的now()方法創(chuàng)建一個表示當前日期的LocalDate對象,然后調(diào)用toString()方法將其轉(zhuǎn)換為字符串,再通過字符串操作獲取年、月和日。

示例代碼:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class GetCurrentDate {
    public static void main(String[] args) {
        // 獲取當前日期的LocalDate對象并格式化為字符串
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String dateString = currentDate.format(formatter);
        
        // 從字符串中解析出年、月和日并輸出結(jié)果
        String[] parts = dateString.split("年");
        int year = Integer.parseInt(parts[0]);
        String[] months = parts[1].split("月");
        int month = Integer.parseInt(months[0]) - 1; // 月份從0開始,所以需要減1
        String[] days = months[1].split("日");
        int day = Integer.parseInt(days[0]);
        
        System.out.println("今天的日期是:" + year + "年" + month + "月" + day + "日");
    }
}

Python中獲取當天的年月日

1. 使用datetime模塊(Python 3.2及以上版本)

Python的標準庫datetime模塊提供了豐富的日期時間處理功能,我們可以使用datetime模塊中的date類來表示不帶時分秒的日期。要獲取當天的年月日,我們可以使用date類的today()方法創(chuàng)建一個表示當前日期的date對象,然后調(diào)用year屬性、month屬性和day屬性分別獲取年、月和日。需要注意的是,在Python中,月份是從0開始的,因此需要對返回的月份加1。

示例代碼:

from datetime import date

# 獲取當前日期的date對象并輸出結(jié)果
today = date.today()
print("今天的日期是:", today.year, "年", today.month + 1, "月", today.day, "日")