[英]Scala date format
I have a data_date that gives a format of yyyymmdd: 我有一个data_date,其格式为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. 这将给我一个结果'20180202',但是对于我的用例,我需要结果为201802(yyyymm)。 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? 我不想更改beginDate的值,我只想更改data_date值以适合我的用例,我该怎么做? 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. 从代码片段中尚不清楚您使用的是Spark,但是这些标记暗示了这一点,因此,我将使用Spark内置函数给出答案。 Suppose your DataFrame
is called df
with date column my_date_column
. 假设您的DataFrame
名为df
,日期my_date_column
。 Then, you can simply use date_format
然后,您只需使用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. 您可以仅采用结果字符串的前6个字符来完成此操作。 ie 即
val s = "20180202"
s.substring(0, 6) // returns "201802"
The way to to it with DateTimeFormatter. 使用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. 我建议您通读DateTimeFormatter
文档,以便以所需的方式格式化日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.