com.hejinonline.util.DateUtil.scala Maven / Gradle / Ivy
The newest version!
package com.hejinonline.util
import java.util.{ Date, Calendar }
import java.text.SimpleDateFormat
object DateUtil {
/**
* 返回当前日期的 年-月-日
*
* year = Array(0)
* mongth = Array(1)
* day = Array(2)
*
*/
def getDayOfYMD(d: Date): Array[Int] = {
val c = Calendar.getInstance
c.setTime(d)
Array(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH))
}
/**
* 返回当前日期的 年-月-日
* 这里只支持 yyyy-MM-dd的字符串
* year = Array(0)
* mongth = Array(1)
* day = Array(2)
*/
def getDayOfYMD(str: String): Array[Int] = {
val d = this.stringToDate(str)
this.getDayOfYMD(d)
}
/**
* 获取日期是星期几
*/
def getDayOfWeek(d: Date): Int = {
val c = Calendar.getInstance
c.setTime(d)
c.get(Calendar.DAY_OF_WEEK)
}
/**
* 获取日期是星期几
*/
def getDayOfWeek(str: String): Int = {
val d = this.stringToDate(str)
this.getDayOfWeek(d)
}
/**
* 只处理这种格式的数据 yyyy-MM-dd
*/
def getDateSpan(str: String, i: Int): Array[Date] = {
val d = this.stringToDate(str);
i match {
case 1 => Array(firstDayOfWeek(d), lastDayOfWeek(d))
case 2 => Array(firstDayOfMonth(d), lastDayOfMonth(d))
case _ => Array(d, d)
}
}
private def lastDayOfWeek(d: Date): Date = {
val c = Calendar.getInstance
c.setTime(d)
c.add(Calendar.DAY_OF_YEAR, 7 - c.get(Calendar.DAY_OF_WEEK)) //找到本周的星期天
c.getTime
}
private def firstDayOfWeek(d: Date): Date = {
val c = Calendar.getInstance
c.setTime(d)
c.add(Calendar.DAY_OF_YEAR, -c.get(Calendar.DAY_OF_WEEK) + 1) //找到本周的星期天
c.getTime
}
private def firstDayOfMonth(d: Date): Date = {
val c = Calendar.getInstance
c.setTime(d)
c.add(Calendar.MONTH, 0)
c.set(Calendar.DAY_OF_MONTH, 1) // 设置为1号,当前日期既为本月第一天
c.getTime
}
private def lastDayOfMonth(d: Date): Date = {
val c = Calendar.getInstance
c.setTime(d)
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
c.getTime
}
/**
* 这里只能处理 yyyy-MM-dd 数据
* 没做数据验证
*/
private def stringToDate(str: String): Date = {
//这里应该验证数据(暂时跳过)
new SimpleDateFormat("yyyy-MM-dd").parse(str)
}
}