fastjson解析json字符串和数组+Scala时间处理

废话不多说直接上代码

1.Json解析

package scala.csdn
import com.alibaba.fastjson.JSON
object ParseJson {
  def main(args: Array[String]): Unit = {
    //解析json字符串
    val jsonStr = "{\"name\":\"Michael\"}"
    val parseJson = JSON.parseObject(jsonStr)
    val name = parseJson.getString("name")
    println(s"解析出的名字是:$name")
    //解析json数组
    val jsonArray = "[{\"name\":\"Andy\", \"age\":30},{\"name\":\"Justin\", \"age\":19}]"
    val parseJsonArray = JSON.parseArray(jsonArray)
    //遍历
    for (i <- 0 until parseJsonArray.size){
      val jsonObject = parseJsonArray.getJSONObject(i)
      val name = jsonObject.getString("name")
      val age = jsonObject.getInteger("age")
      println(s"$name's age is $age")
    }
  }
}

2.时间处理

package scala.csdn
import java.text.SimpleDateFormat
import java.util.{Date, Calendar}
object DateProcess {
  def main(args: Array[String]): Unit = {
    println(getNowTimeStamp())
    println(getNowDate())
    println(timeStamp2Date(1567002778))
    println(Date2TimeStamp("2019-08-28 22:32:58"))
    println(getPastDayDate(2))
    println(getTwoDateDiffSeconds("2019-08-28 21:32:58":String, "2019-08-28 22:32:58":String))
  }

  def getNowTimeStamp():Long = {
    //当前时间戳:秒
    val now = new Date()
    now.getTime / 1000
  }
  def getNowDate():String = {
    //当前时间日期:时分秒可自行设置日期格式
    val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val now = new Date()
    dateFormat.format(now)
  }
  def timeStamp2Date(timeStamp:Long):String = {
    //时间戳转日期
    val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val date = new Date(timeStamp * 1000)
    dateFormat.format(date)
  }
  def Date2TimeStamp(date:String):Long = {
    //日期转时间戳
    val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val dateParse = dateFormat.parse(date)
    dateParse.getTime / 1000
  }
  def getPastDayDate(days:Int):String = {
    //获取过去或者未来几天后的日期:正数表示过去days的日期,负数表示未来几天后的日日期
    val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    //val dateFormat = new SimpleDateFormat("yyyy-MM-dd")
    val cal = Calendar.getInstance()
    cal.add(Calendar.DATE, -days)
    dateFormat.format(cal.getTime)
  }
  def getTwoDateDiffSeconds(LowerDateString:String, BiggerDateString:String):Long = {
    //两个日期的时间差:秒可自行计算转换为小时分钟等
    val start = Date2TimeStamp(LowerDateString)
    val end = Date2TimeStamp(BiggerDateString)
    end - start
  }
}

你可能感兴趣的:(scala,fastjson,时间)