上一篇                     
               
			  Java如何获取两位年份?
- 后端开发
- 2025-06-06
- 4488
 在Java中获取两位年份可使用
 
 
SimpleDateFormat或
 DateTimeFormatter:,“
 java,// 旧版API,SimpleDateFormat sdf = new SimpleDateFormat("yy");,String twoDigitYear = sdf.format(new Date());,// Java 8+,String twoDigitYear = LocalDate.now().format(DateTimeFormatter.ofPattern("yy"));,“,这两种方法均从当前日期提取后
 两位年份(如2025年返回”24″),注意线程安全性和时区设置。
在Java中获取两位数的年份是处理日期时的常见需求,尤其在格式化报表、文件名或数据库存储时,以下是几种高效可靠的方法,结合线程安全和时区处理等关键考量,确保代码健壮性:
方法1:使用 SimpleDateFormat(兼容旧版Java)
 
适用于Java 8之前的版本,但需注意非线程安全(避免全局共享实例):
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yy"); // "yy"表示两位年份
        String twoDigitYear = sdf.format(new Date());
        System.out.println("两位年份: " + twoDigitYear); // 示例: "24"(2025年)
    }
} 
方法2:java.time 包(Java 8+ 推荐方案)
 
线程安全且功能更强大,官方推荐优先使用:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
    public static void main(String[] args) {
        // 方案1:直接获取年份后取模
        int year = LocalDate.now().getYear() % 100; // 取后两位
        String twoDigitYear = String.format("%02d", year); // 格式化为两位数
        System.out.println("两位年份: " + twoDigitYear); // "24"
        // 方案2:通过格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy");
        String formattedYear = LocalDate.now().format(formatter);
        System.out.println("格式化年份: " + formattedYear); // "24"
    }
} 
方法3:Calendar 类(过渡方案)
 
适合旧项目迁移,但比 java.time 繁琐:
import java.util.Calendar;
public class Main {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        int fullYear = cal.get(Calendar.YEAR);     // 获取完整年份(如2025)
        int twoDigitYear = fullYear % 100;         // 取后两位
        System.out.println("两位年份: " + twoDigitYear); // 24
    }
} 
️ 关键注意事项
-  线程安全:  - SimpleDateFormat和- Calendar非线程安全,避免全局静态共享。
- java.time包下的类(如- LocalDate,- DateTimeFormatter)均为不可变对象,可安全并发使用。
 
-  时区处理: - 默认使用系统时区,需显式指定时区时: LocalDate.now(ZoneId.of("Asia/Shanghai")); // 指定上海时区
 
- 默认使用系统时区,需显式指定时区时: 
-  年份范围:  - SimpleDateFormat的- yy会将 2025 转为 “24”,但 2000 年前年份可能需额外处理(如 1999 → “99”)。
 
-  补零显示: - 使用 String.format("%02d", year)确保个位数年份显示为 “01”、”02″ 等格式。
 
- 使用 
最佳实践建议
| 场景 | 推荐方案 | 优势 | 
|---|---|---|
| Java 8+ 新项目 | java.time包 | 线程安全、API 丰富 | 
| 旧系统维护 | SimpleDateFormat | 兼容性高,但需隔离实例 | 
| 简单计算无需格式化 | Calendar+ 取模 | 无额外依赖 | 
- 优先选择 java.time(如LocalDate+DateTimeFormatter),兼顾安全性与功能性。
- 旧版项目用 SimpleDateFormat时,务必每次创建新实例或通过ThreadLocal隔离。
- 明确业务是否需要补零、时区校正等细节,避免逻辑错误。
引用说明:本文代码基于 Oracle 官方 Java 17 文档,日期处理规范参考 Java Time API 和 DateTimeFormatter 模式定义。
 
  
			 
			 
			 
			 
			 
			 
			 
			