Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java 获取当前年月

作者:徒醉了清风   发布日期:2025-02-06   浏览:91

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();

        // 定义格式化模式为年月,例如:2023-10
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        // 格式化当前日期时间为指定的年月格式
        String currentYearMonth = now.format(formatter);

        // 输出结果
        System.out.println("当前年月: " + currentYearMonth);
    }
}

解释说明:

  1. 导入必要的类LocalDateTimeDateTimeFormatter 是 Java 8 引入的时间处理类,用于获取当前日期时间和格式化日期。
  2. 获取当前日期时间:使用 LocalDateTime.now() 获取当前的日期和时间。
  3. 定义格式化模式:使用 DateTimeFormatter.ofPattern("yyyy-MM") 定义一个格式化模式,将日期格式化为“年-月”的形式。
  4. 格式化当前日期时间:通过 now.format(formatter) 将当前日期时间格式化为指定的年月格式。
  5. 输出结果:使用 System.out.println 输出格式化后的年月。

上一篇:java 遍历数组

下一篇:java double转integer

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站