【问题标题】:In Scala - How to get the day of the week?在 Scala 中 - 如何获取星期几?
【发布时间】:2017-05-20 18:59:28
【问题描述】:

假设我的日期格式是 21/05/2017,那么输出将是 SUN。

我怎样才能得到给定日期的日期?

【问题讨论】:

    标签: scala


    【解决方案1】:

    您可以使用SimpleDateFormat,如下图所示:

    import java.util.Calendar
    import java.text.SimpleDateFormat
    
    val now = Calendar.getInstance.getTime
    
    val date = new SimpleDateFormat("yyyy-MM-dd")
    date.format(now)
    res1: String = 2017-05-20
    
    val dowInt = new SimpleDateFormat("u")
    dowInt.format(now)
    res2: String = 6
    
    val dowText = new SimpleDateFormat("E")
    dowText.format(now)
    res3: String = Sat
    

    [更新]

    根据下面的 cmets,请注意 SimpleDateFormat 不是线程安全的。

    【讨论】:

    • @Zernike,你是对的,即使线程安全不是 OP 中的要求,我想是时候放弃我们许多人已经习惯的旧 API。
    【解决方案2】:
        import java.time.LocalDate
        import java.time.format.DateTimeFormatter
    
        val df = DateTimeFormatter.ofPattern("dd/MM/yyyy")
        val dayOfWeek = LocalDate.parse("21/05/2017",df).getDayOfWeek
    

    【讨论】:

      【解决方案3】:

      您还可以使用 nscala-time,它是 Java 的 joda-time 的 Scala 包装器,它是一个具有大量功能的日期时间库。

      import com.github.nscala_time.time.Imports._
      
      val someDate =(newDateTime).withYear(2017)
                                 .withMonthOfYear(5)
                                 .withDayOfMonth(21)
      
      someDate.getDayOfWeek
      
      res7: Int = 7
      

      现在您需要知道一周中的整数天数与名称之间的映射。这里,7 对应于星期日。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-19
        • 2016-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-18
        • 2019-09-22
        • 1970-01-01
        相关资源
        最近更新 更多