网站首页 网站地图
网站首页 > 娱乐人生 > 年月日怎么编程

年月日怎么编程

时间:2026-03-17 17:34:15

在不同的编程语言中,获取和格式化年月日的方法有所不同。以下是几种常见编程语言的示例代码:

Python

```python

import datetime

获取当前日期

current_date = datetime.date.today()

提取年、月、日

year = current_date.year

month = current_date.month

day = current_date.day

打印结果

print("当前日期:", current_date)

print("年:", year)

print("月:", month)

print("日:", day)

```

Java

```java

import java.time.LocalDate;

public class Main {

public static void main(String[] args) {

// 获取当前日期

LocalDate currentDate = LocalDate.now();

// 提取年、月、日

int year = currentDate.getYear();

int month = currentDate.getMonthValue();

int day = currentDate.getDayOfMonth();

// 打印结果

System.out.println("当前日期: " + currentDate);

System.out.println("年: " + year);

System.out.println("月: " + month);

System.out.println("日: " + day);

}

}

```

C

```csharp

using System;

class Program

{

static void Main()

{

// 获取当前日期

DateTime currentDate = DateTime.Now;

// 提取年、月、日

int year = currentDate.Year;

int month = currentDate.Month;

int day = currentDate.Day;

// 打印结果

Console.WriteLine("当前日期: " + currentDate);

Console.WriteLine("年: " + year);

Console.WriteLine("月: " + month);

Console.WriteLine("日: " + day);

}

}

```

JavaScript (Node.js)

```javascript

const datetime = require('date-fns');

// 获取当前日期

const currentDate = new Date();

// 提取年、月、日

const year = currentDate.getFullYear();

const month = currentDate.getMonth() + 1; // 月份从0开始,所以需要加1

const day = currentDate.getDate();

// 打印结果

console.log("当前日期:", currentDate.toISOString().split('T'));

console.log("年:", year);

console.log("月:", month);

console.log("日:", day);

```

C

```c

include

include

int main() {

time_t t = time(NULL);

struct tm *now = localtime(&t);

// 提取年、月、日

int year = now->tm_year + 1900;

int month = now->tm_mon + 1; // 月份从0开始,所以需要加1

int day = now->tm_mday;

// 打印结果

printf("当前日期: %d-%02d-%02d\n", year, month, day);

return 0;

}

```

输入日期并转换格式

```c

include

include

int main() {

char date;

printf("输入一个日期 (月/日/年): ");

scanf("%s", date);

int month, day, year;

sscanf(date, "%d/%d/%d", &month, &day, &year);

// 打印结果

printf("%d年%d月%d日\n", year, month, day);

return 0;

}

```

这些示例代码展示了如何在不同编程语言中获取和格式化年月日。你可以根据具体需求选择合适的编程语言和代码示例。