简体   繁体   中英

Scala date format

I have a data_date that gives a format of yyyymmdd:

beginDate = Some(LocalDate.of(startYearMonthDay(0), startYearMonthDay(1), 
startYearMonthDay(2)))
var Date = beginDate.get
.......

val data_date = Date.toString().replace("-", "")

This will give me a result of '20180202' however, I need the result to be 201802 (yyyymm) for my usecase. I don't want to change the value of beginDate, I just want to change the data_date value to fit my usecase, how do I do that? is there a split function I can use? Thanks!

It's not clear from the code snippet that you're using Spark, but the tags imply that, so I'll give an answer using Spark built-in functions. Suppose your DataFrame is called df with date column my_date_column . Then, you can simply use date_format

scala> import org.apache.spark.sql.functions.date_format
import org.apache.spark.sql.functions.date_format

scala> df.withColumn("my_new_date_column", date_format($"my_date_column", "YYYYMM")).
     | select($"my_new_date_column").limit(1).show

// for example:
+------------------+
|my_new_date_column|
+------------------+
|            201808|
+------------------+

You can do this by only taking the first 6 characters of the resulting string. ie

val s = "20180202"
s.substring(0, 6) // returns "201802"

The way to to it with DateTimeFormatter.

val formatter = DateTimeFormatter.ofPattern("YMM")
val data_date = Date.format(foramatter)

I recommend you to read through DateTimeFormatter docs, so you can format date the way you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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