简体   繁体   English

Scala中的日期转换问题

[英]Date conversion issue in scala

I have a scenario where I have to get difference between the current date with the dates in a column from the dataframe . 我有一种情况,我必须获取当前日期与dataframe列中的日期之间的差。 I am facing an issue when I took the current date which is in localDate format and the date from dataframe are in date datatype. 我现在面临一个问题,当我把当前的日期是在localDate format和日期dataframe是日期数据类型。

Also I have tried to convert current day to string and and convert the data from dataframe to string but am not getting expected output as dates should be compared with date datatypes. 我也试图将当前日期转换为字符串,并将数据从dataframe to string转换dataframe to string但是由于日期应该与日期数据类型进行比较,因此没有得到预期的输出。

I have used the below code: 我使用了以下代码:

import java.time.LocalDate
val localDate = LocalDate.now 

def computeCarAge(importvoices:DataFrame): DataFrame = {

val computeCarAgeUDF = udf (
    (aged: Date) =>
      if (aged < localDate ) {
        "from0to1year"
      } else if (aged <= localDate) {
        "from1to2years" }
)

How to compare java local date to spark.sql.date which is in (yyyy-MM-dd) format? 如何将java local date(yyyy-MM-dd)格式的spark.sql.date比较?

You can convert the localDate of Java to Date datatype and then compare with your dataframe date. 您可以将Java的localDate转换为Date数据类型,然后将其与数据框日期进行比较。 The sample code to convert LocalDate to Date Datatype is: 将LocalDate转换为Date数据类型的示例代码为:

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

The code sample is in Java but you can write the scala version of it :) 该代码示例使用Java,但是您可以编写它的Scala版本:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM