【问题标题】:scala loop to add date string into a seqscala循环将日期字符串添加到seq中
【发布时间】:2021-04-09 07:31:29
【问题描述】:

我正在尝试将字符串中的日期从一个数组添加到一个序列中,同时确定它是否是周末。

import java.text.SimpleDateFormat
import java.util.{Calendar, Date, GregorianCalendar}
import org.apache.spark.sql.SparkSession

val arrDateEsti=dtfBaseNonLong.select("AAA").distinct().collect.map(_(0).toString);
    
var dtfDateCate = Seq(
      ("0000", "0")
    );
    
for (a<-0 to arrDateEsti.length-1){
      val dayDate:Date = dateFormat.parse(arrDateEsti(a));
      val cal=new GregorianCalendar
      cal.setTime(dayDate);
    
  if (cal.get(Calendar.DAY_OF_WEEK)==1 || cal.get(Calendar.DAY_OF_WEEK)==7){
    dtfDateCate:+(arrDateEsti(a),"1")
  }else{
    dtfDateCate:+(arrDateEsti(a),"0")
  }
};

scala> dtfDateCate
res20: Seq[(String, String)] = List((0000,0))

它返回相同的初始序列。但是,如果我运行一个元素,它就可以工作。出了什么问题?

scala>   val dayDate:Date = dateFormat.parse(arrDateEsti(0));
dayDate: java.util.Date = Thu Oct 15 00:00:00 CST 2020

scala>   cal.setTime(dayDate);

scala>   if (cal.get(Calendar.DAY_OF_WEEK)==1 || cal.get(Calendar.DAY_OF_WEEK)==7){
     |     dtfDateCate:+(arrDateEsti(0),"1")
     |   }else{
     |     dtfDateCate:+(arrDateEsti(0),"0")
     |   };
res14: Seq[(String, String)] = List((0000,0), (20201015,0))

【问题讨论】:

  • SimpleDateFormatjava.util 库用于 DateCalendar 已经相当陈旧和过时了。它们是您的代码的要求吗?
  • 您的if 评估返回一个附加的Seq[] 值,但它没有被保存或收集,所以它只是被丢弃了。你没有以任何方式修改dtfDateCate
  • simpleDateFormat 不是必需的。如果您知道任何更好的确定日期的方法,请告诉我

标签: scala loops calendar seq


【解决方案1】:

我认为这正是你想要做的。

import java.time.LocalDate
import java.time.DayOfWeek.{SATURDAY, SUNDAY}
import java.time.format.DateTimeFormatter

                  //replace with dtfBaseNonLong.select(... code
val arrDateEsti = Seq("20201015", "20201017")  //place holder

val dtFormat = DateTimeFormatter.ofPattern("yyyyMMdd")
val dtfDateCate = ("0000", "0") +:
                  arrDateEsti.map { dt =>
                    val day = LocalDate.parse(dt,dtFormat).getDayOfWeek()
                    if (day == SATURDAY || day == SUNDAY) (dt, "1")
                    else                                  (dt, "0")
                  }
//dtfDateCate = Seq((0000,0), (20201015,0), (20201017,1))

【讨论】:

    【解决方案2】:

    是的,应该是seqDateCate=seqDateCate:+(arrDateEsti(a),"1")

    【讨论】:

    • 突变。糟糕的 Scala 风格。尽可能避免(而且几乎总是有可能)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2014-06-05
    • 2015-07-31
    相关资源
    最近更新 更多