In Scala - How to get the day of the week?

谁说我不能喝 提交于 2021-02-10 14:43:55

问题


Suppose my date format is 21/05/2017 then the output will be SUN.

How can I get the day given a date?


回答1:


    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



回答2:


You can use SimpleDateFormat as illustrated below:

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

[UPDATE]

As per comments below, please note that SimpleDateFormat isn't thread-safe.




回答3:


You can also use nscala-time which is a Scala wrapper for Java's joda-time which is a datetime library with a ton of functionality.

import com.github.nscala_time.time.Imports._

val someDate =(newDateTime).withYear(2017)
                           .withMonthOfYear(5)
                           .withDayOfMonth(21)

someDate.getDayOfWeek

res7: Int = 7

Now you need to know the mapping between integer days of the week and names. Here, 7 corresponds to Sunday.



来源:https://stackoverflow.com/questions/44089758/in-scala-how-to-get-the-day-of-the-week

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!