如何在Scala中编写CurrentYear和PreviousYear函数?
正确实现日期/年份获取的Scala函数
首先,不推荐使用Calendar和SimpleDateFormat这类旧Java API,它们存在线程不安全、API设计繁琐的问题。更推荐使用Java 8引入的java.time包(Scala完全兼容),实现更简洁安全。
推荐实现(基于Java 8+ java.time)
import java.time.LocalDate import java.time.format.DateTimeFormatter // 获取当前日期(格式:yyyyMMdd) def getCurrentDate: String = { val formatter = DateTimeFormatter.ofPattern("yyyyMMdd") LocalDate.now().format(formatter) } // 获取当前年份(格式:yyyy) def getCurrentYear: String = { LocalDate.now().getYear.toString } // 获取上一年份(格式:yyyy) def getPreviousYear: String = { LocalDate.now().minusYears(1).getYear.toString }
代码说明
LocalDate.now():直接获取当前系统日期,线程安全,无需手动维护日历实例DateTimeFormatter.ofPattern("yyyyMMdd"):定义日期格式化规则,线程安全可复用getYear.toString:直接提取年份并转为字符串,无需多余的日期格式化操作minusYears(1):对当前日期做减一年操作,轻松得到上一年的日期后提取年份
兼容旧API的实现(不推荐)
如果必须使用旧API,可修正原代码的问题:
import java.util.Calendar import java.text.SimpleDateFormat def getCurrentDate: String = { val cal = Calendar.getInstance() new SimpleDateFormat("yyyyMMdd").format(cal.getTime()) } def getCurrentYear: String = { val cal = Calendar.getInstance() new SimpleDateFormat("yyyy").format(cal.getTime()) } def getPreviousYear: String = { val cal = Calendar.getInstance() cal.add(Calendar.YEAR, -1) new SimpleDateFormat("yyyy").format(cal.getTime()) }
注意:SimpleDateFormat是非线程安全的,多线程环境下使用需额外处理(比如每次创建实例)。
内容的提问来源于stack exchange,提问作者Joshi Tharun
相关产品推荐
相关产品推荐

