在 Databricks 上使用 Spark Scala,我试图创建一个包含当月第一天的变量。
在第一步中,我只获取当前日期,它工作正常:
val current_date = LocalDate.now()
这给了我正确的输出,例如:
current_date: java.time.LocalDate = 2022-05-02
我的问题是当我试图获取当月的第一天时。我试过使用 TemporalAdjuster ,但它不起作用。任何人都可以告诉我正确的方法吗?
我尝试过的例子:
val current_month = current_date.temporal(TemporalAdjuster.firstDayOfMonth())
>>> error: value temporal is not a member of java.time.LocalDate
val current_month = current_date.temporal(TemporalAdjuster.firstDayOfMonth())
>>> error: value firstDayOfMonth is not a member of object java.time.temporal.TemporalAdjuster
val current_month = current_date.temporal(TemporalAdjuster.firstDayOfMonth())
val current_month = current_date.with(TemporalAdjuster.firstDayOfMonth())
>>> error: identifier expected but 'with' found.
val current_month = current_date.with(TemporalAdjuster.firstDayOfMonth())
^
最佳答案
最简单的方法是使用date_trunc
函数将当前日期四舍五入到给定的粒度。要获得第一天,您需要将当前日期截断为一个月级别,如下所示(我们需要使用 to_date
因为 date_trunc
返回时间戳):
to_date(date_trunc( "mon", current_date()))
例如,如果您在 Databricks 上按如下方式运行它:
display(spark.range(3).withColumn("first_day",
to_date(date_trunc( "mon", current_date()))))
你会得到
关于java - 如何在 Databricks Spark Scala 中使用当月的第一天创建变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72085981/