1. Overview

In this tutorial, we’ll learn how to get the week of the year from a date in Scala. We’ll look into doing this using the newest Java Date-Time API library released with Java 8, as developers have been strongly encouraged to migrate from java.util.Date library to the new Date-Time API instead.

2. Creating Dates

Let’s start by defining a few different dates with the Java Date-Time API:

scala> import java.time._
import java.time._

scala> val janDate = LocalDate.of(2020, Month.JANUARY, 8)
janDate: java.time.LocalDate = 2020-01-08

scala> val marDate = LocalDate.of(2020, Month.MARCH, 15)
marDate: java.time.LocalDate = 2020-03-15

scala> val sepDate = LocalDate.of(2020, Month.SEPTEMBER, 30)
sepDate: java.time.LocalDate = 2020-09-30

Now we have a few dates to test our solution.

3. Get the Week of the Year

To get the week of the year from a given Java date in Scala, we can make use of the library methods:

scala> import java.time.temporal.WeekFields
import java.time.temporal.WeekFields

scala> janDate.get(WeekFields.ISO.weekOfYear())
res5: Int = 2

scala> marDate.get(WeekFields.ISO.weekOfYear())
res6: Int = 11

scala> sepDate.get(WeekFields.ISO.weekOfYear())
res7: Int = 40

The LocalDate.get(TemporalField) method allows us to get many different temporal fields, such as the week of the year, a quarter of the year, the day of the quarter, and others as described in the documentation.

4. Conclusion

In this article, given a date, we learned how to get the week of the year using the Java Date-Time API. If you need to use the older Java Date API, check out our article, Getting the Week Number From Any Date.


» 下一篇: 反转 Scala 字符串