如何在Java中获取当前年份

在Java语言中获取当前年份有几种方法:使用java.util包下的Calendar类,使用java.time包下的LocalDate类或者使用java.text包下的SimpleDateFormat类。

一、使用java.util.Calendar类获取当前年份

java.util类库中的Calendar类包含关于日期时间的信息,我们可以通过其提供的方法获取到当前的年份。

import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        System.out.println("Current Year is : " + year);
    }
}

在上述代码中,首先通过Calendar类的getInstance方法获取一个Calendar实例,然后调用其get方法并传入参数Calendar.YEAR来获取当前年份。

二、使用java.time.LocalDate类获取当前年份

在Java 8之后,java.time包被引入,其中的LocalDate类也可以用来获取当前年份。

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        System.out.println("Current year is : " + year);
    }
}

在这段代码中,首先通过LocalDate类的now方法获取一个LocalDate实例,然后调用其getYear方法来获取当前年份。

三、使用java.text.SimpleDateFormat类获取当前年份

java.text包中的SimpleDateFormat类可以用来获取日期的字符串表示形式,也可以用于解析这些字符串。通过使用合适的格式模式,我们也可以得到当前的年份。

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String year = sdf.format(new Date());
        System.out.println("Current year is : " + year);
    }
https://www.10zhan.com

在这段代码中,首先创建了一个SimpleDateFormat对象,然后使用它的format方法和当前的日期,得到一个表示当前年份的字符串。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值