开发者社区> 问答> 正文

play 框架中如何在anorm 解析数据库结果时进行datetime格式转换?

从MySQL取得的数据里有一项是time,取回来的是“yyyy-MM-dd HH:mm:ss”格式的java.sql.timestamp类型的数据,我有下面的代码把time转换成为joda.DateTime类型的数据,然后转为字符串传给前端,但是发现转换成了一串数字的timestamp形式,但是前端需要展示“yyyy-MM-dd HH:mm:ss”格式的时间。请问在服务器后台怎么进行这个格式化?
下面是我的代码。

import org.joda.time.DateTime

import anorm.SqlParser._
import anorm._
import play.api.db.DB
import play.api.libs.functional.syntax._
import play.api.libs.json._
import play.api.Play.current

/**
 * Created by zsh on 2015/5/11.
 */
case class JDItem(
                  id: Long,//商品ID
                  name: String,//商品名称
                  url: String,//商品url
//                  imgsrc: String,//商品图片(url)
                  price: Double,//商品价格
                  commentnum: Int,//商品评论数
                  likerate:Int,//好评率
                  time:DateTime,//上架时间
//                  wareInfo: String,//产品特色介绍(图文)
//                  wareStandard: String,//产品规格
//                  warePack:String,//产品包装
//                  wareService:String,//产品售后
                  category:String)

object JDItem {

  val jditem = {
    get[Long]("id") ~
    get[String]("name") ~
    get[String]("url") ~
    get[Double]("price") ~
    get[Int]("commentnum") ~
    get[Int]("likerate") ~
    get[DateTime]("time") ~
    get[String]("category") map {
      case id ~ name ~ url ~price~
        commentnum~likerate~time~category => JDItem(id,name,url,price,
        commentnum,likerate,time,category)
    }
  }

  implicit val JDItemWrites: Writes[JDItem] = (
    (JsPath \ "id").write[Long] and
      (JsPath \ "name").write[String] and
      (JsPath \ "url").write[String] and
      (JsPath \ "price").write[Double] and
      (JsPath \ "commentnum").write[Int] and
      (JsPath \ "likerate").write[Int] and
      (JsPath \ "time").write[DateTime] and
      (JsPath \ "category").write[String]
    )(unlift(JDItem.unapply))

  def getJson(category:String,sort:String,DescOrAsc:String):JsObject = DB.withConnection{ implicit c =>
    val list = SQL("select id,name,url,price,commentnum,likerate,time,category from "+category+" order by "+sort+" "+DescOrAsc+" limit 100").as(jditem *)
    val json:JsValue = Json.toJson(list)
    val jsobject = Json.obj("total"-> list.length,"rows"-> json)
    println("发送的字符串是========"+jsobject.toString())
    jsobject
  }

  def all(): List[String] = DB.withConnection { implicit c =>
    SQL("show tables").as(get[String]("table_name") *)
  }
}

展开
收起
蛮大人123 2016-02-11 23:21:48 3106 0
0 条回答
写回答
取消 提交回答
问答排行榜
最热
最新

相关电子书

更多
神龙云服务器产品及技术深度解析 立即下载
弹性创造价值:基于ECS的最佳性价比实践解析 立即下载
又快又稳:阿里云下一代虚拟交换机解析 立即下载

相关镜像