Scala日期操作、获取当前时间、获取前一天时间、获取两日期时间差、获取两日期间所有日期

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-1 18:44   11   0

获取当前时间

var dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd")
var cal: Calendar = Calendar.getInstance()
val nowday = dateFormat.format(cal.getTime())
println(nowday)

获取前1天日期

val date = "2020-09-13"
val myformat = new SimpleDateFormat("yyyy-MM-dd")
var dnow = new Date()
dnow = myformat.parse(date)
val cal1 = Calendar.getInstance()
cal1.setTime(dnow)
cal1.add(Calendar.DATE, -1)
println(myformat.format(cal1.getTime()))

获取两日期时间差

    val dateFormat = new SimpleDateFormat("yyyyMMdd")
    val st = dateFormat.parse("20200101")
    val end = dateFormat.parse("20200104")
    val tm1 = st.getTime
    val tm2 = end.getTime
    val btDays = (tm2-tm1)/(1000*3600*24)

获取两日期间所有日期

/**
    * 获取两个日期之间的日期
    *
    * @param start 开始日期
    * @param end   结束日期
    * @return 日期集合
    */
  def getBetweenDates(start: String, end: String) = {
    val startData = new SimpleDateFormat("yyyy-MM-dd").parse(start); //定义起始日期
    val endData = new SimpleDateFormat("yyyy-MM-dd").parse(end); //定义结束日期

    val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyyMMdd")
    var buffer = new ListBuffer[String]
    buffer += dateFormat.format(startData.getTime())
    val tempStart = Calendar.getInstance()

    tempStart.setTime(startData)
    tempStart.add(Calendar.DAY_OF_YEAR, 1)

    val tempEnd = Calendar.getInstance()
    tempEnd.setTime(endData)
    while (tempStart.before(tempEnd)) {
      // result.add(dateFormat.format(tempStart.getTime()))
      buffer += dateFormat.format(tempStart.getTime())
      tempStart.add(Calendar.DAY_OF_YEAR, 1)
    }
    buffer += dateFormat.format(endData.getTime())
    buffer.toList
  }

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP