scala 时间、时间戳系列操作

格式说明:

LetterDate or Time ComponentPresentationExamples
GEra designatorTextAD
yYearYear199696
YWeek yearYear200909
MMonth in yearMonthJulyJul07
wWeek in yearNumber27
WWeek in monthNumber2
DDay in yearNumber189
dDay in monthNumber10
FDay of week in monthNumber2
EDay name in weekTextTuesdayTue
uDay number of week (1 = Monday, ..., 7 = Sunday)Number1
aAm/pm markerTextPM
HHour in day (0-23)Number0
kHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978
zTime zoneGeneral time zonePacific Standard TimePSTGMT-08:00
ZTime zoneRFC 822 time zone-0800
XTime zoneISO 8601 time zone-08-0800-08:00

格式示例:

Date and Time PatternResult
"yyyy.MM.dd G 'at' HH:mm:ss z"2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy"Wed, Jul 4, '01
"h:mm a"12:08 PM
"hh 'o''clock' a, zzzz"12 o'clock PM, Pacific Daylight Time
"K:mm a, z"0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa"02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z"Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ"010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u"2001-W27-3
"自由输入YYYY-'爱你哦'ww-u自由输入"自由输入2001-爱你哦27-3自由输入
import java.text.SimpleDateFormat
import java.util.{Calendar, Date}

/**
      * 获取当前时间
      *
      * @param pattern pattern 如"yyyyMMddHHmmss"
      * @return
      */
    def getrealTime(pattern: String): String = {
        val timeTag = System.currentTimeMillis()
        val changeTime = new Date(timeTag)
        val dataFormat = new SimpleDateFormat(pattern)
        dataFormat.format(changeTime)
    }

/**
      * 获取当前时间戳(精确到毫秒)
      *
      * @return
      */
    def getTimestamp(): Long = {
        val time = Util.getrealTime("yyyyMMddHHmmss")
        Util.funStringToTimeStamp(time, "yyyyMMddHHmmss")
    }




    /**
      * 将时间字符串修改为时间戳
      *
      * @param time          时间
      * @param timeFormatted 时间格式 如 "yyyyMMddHHmmss"
      * @return 精确到毫秒的时间戳
      */
    def funStringToTimeStamp(time: String, timeFormatted: String): Long = {
        val fm = new SimpleDateFormat(timeFormatted)
        val dt = fm.parse(time)
        dt.getTime
    }

    /**
      * 将时间戳转换为时间
      *
      * @param timestamp     精确到毫秒
      * @param timeFormatted 时间格式如“HH”表示按24小时制返回时间戳对应的小时
      * @return
      */
    def timestampToString(timestamp: String, timeFormatted: String): String = {
        val fm = new SimpleDateFormat(timeFormatted)
        val time = fm.format(new Date(timestamp.toLong))
        time
    }
 /**
      * 获取传入日期与当前日期的天数差
      *
      * @param day          待比较日期(仅包含月日)
      * @param dayFormatted 待比较日期格式(例如:MMdd或MM-dd)
      * @return
      */
    def daysBetweenToday(day: String, dayFormatted: String): Int = {
        val calendar = Calendar.getInstance
        calendar.setTime(new Date())
        val today = calendar.get(Calendar.DAY_OF_YEAR)
        val year = calendar.get(Calendar.YEAR)
        val inputF = new SimpleDateFormat("yyyy" + dayFormatted)
        val date = inputF.parse(year + day)
        calendar.setTime(date)
        val inputDay = calendar.get(Calendar.DAY_OF_YEAR)
        var days = today - inputDay
        if (days < 0) {
            val beforeYearDate = inputF.parse((year - 1) + day)
            calendar.setTime(beforeYearDate)
            days = calendar.getActualMaximum(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR) + today
        }
        return days
    }

/**
      * 将毫秒级时间戳转化成分钟级时间戳
      *
      * @param time 毫秒级时间戳
      * @return 分钟级时间戳
      */
    def getMinTimestamp(time: Long): Long = {
        val minTime = time / (1000 * 60)
        minTime
    }

  /**
      * 将时间字符串修改为格式
      *
      * @param inpuTime        输入时间
      * @param inputFormatted  输入时间格式
      * @param outputFormatted 输出时间格式
      * @return
      */
    def formatTime(inpuTime: String, inputFormatted: String, outputFormatted: String): String = {
        val inputF = new SimpleDateFormat(inputFormatted)
        val outputF = new SimpleDateFormat(outputFormatted)
        val inputT = inputF.parse(inpuTime)
        outputF.format(inputT)
    }


/**
      * 获取传入时间戳的天数差
      *
      * @param t1 较小时间戳
      * @param t2 较大时间戳
      * @return
      */
    def caculate2Days(t1: Long, t2: Long): Int = {
        import java.util.Calendar
        val calendar = Calendar.getInstance
        calendar.setTimeInMillis(t2)
        val t2Day = calendar.get(Calendar.DAY_OF_YEAR)
        calendar.setTimeInMillis(t1)
        val t1Day = calendar.get(Calendar.DAY_OF_YEAR)
        var days = t2Day - t1Day
        if (days < 0) {
            days = calendar.getActualMaximum(Calendar.DAY_OF_YEAR) - t1Day + t2Day
        }
        return days;
    }

    /**
      * 判断nowTime是否在startTime与endTime之间
      * @param nowTime
      * @param startTime
      * @param endTime
      * @param formater
      * @return
      */
    def isBetweenDate(nowTime: String, startTime: String, endTime: String, formater: String): Boolean = {
        val df = new SimpleDateFormat(formater)
        val nowDate = df.parse(nowTime)
        val startDate = df.parse(startTime)
        val endDate = df.parse(endTime)
        if ((nowDate.getTime == startDate.getTime) || (nowDate.getTime == endDate.getTime)) return true
        if (nowDate.after(startDate) && nowDate.before(endDate)) {
            true
        } else {
            false
        }
    }

     


 /**
      * 时间增加天数,返回时间
      *
      * @param date 入参时间
      * @param num  增加的天数
      * @return
      */
    def funAddDate(date: String, num: Int): String = {
        val myformat = new SimpleDateFormat("yyyyMMdd")
        var dnow = new Date()
        dnow = myformat.parse(date)
        val cal = Calendar.getInstance()
        cal.setTime(dnow)
        cal.add(Calendar.DAY_OF_MONTH, num)
        val newday = cal.getTime
        myformat.format(newday)
    }

    /**
      * 时间增加小时,返回时间
      *
      * @param date 入参时间
      * @param num  增加的天数
      * @return
      */
    def funAddHour(date: String, num: Int): String = {
        val myformat = new SimpleDateFormat("yyyyMMddHH")
        var dnow = new Date()
        dnow = myformat.parse(date)
        val cal = Calendar.getInstance()
        cal.setTime(dnow)
        cal.add(Calendar.HOUR, num)
        val newday = cal.getTime
        myformat.format(newday)
    }

/**
      * 时间增加分钟,返回时间
      *
      * @param date 入参时间
      * @param num  增加的分钟数
      * @return
      */
    def funAddMinute(date: String, num: Int): String = {
        val myformat = new SimpleDateFormat("yyyyMMddHHmm")
        var dnow = new Date()
        dnow = myformat.parse(date)
        val cal = Calendar.getInstance()
        cal.setTime(dnow)
        cal.add(Calendar.MINUTE, num)
        val newday = cal.getTime
        myformat.format(newday)
    }
 /**
      * 时间增加秒,返回时间
      *
      * @param date 入参时间
      * @param num  增加的秒数
      * @return
      */
    def funAddSecond(date: String, num: Int, format: String): String = {
        val myformat = new SimpleDateFormat(format)
        var dnow = new Date()
        dnow = myformat.parse(date)
        val cal = Calendar.getInstance()
        cal.setTime(dnow)
        cal.add(Calendar.SECOND, num)
        val newday = cal.getTime
        myformat.format(newday)
    }


    /** 获取过去几天的时间数组
      *
      * @param date
      * @param num
      * @return
      */
    def getPastDays(date: String, num: Int): Array[String] = {
        val buffer = new ArrayBuffer[String]()
        val range = 0 until num
        for(i <- range){
            buffer.append(funAddDate(date,-i))
        }
        buffer.toArray
    }

    /** 获取过去几小时的时间数组
      *
      * @param date
      * @param num
      * @return
      */
    def getPastHours(date: String, num: Int, interval:Int): Array[String] = {
        val buffer = new ArrayBuffer[String]()
        val range = 0 until num
        for(i <- range){
            buffer.append(funAddHour(date,-i*interval))
        }
        buffer.toArray
    }



 

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值