保存时间
思路:
-
前端传时间戳,
-
后台表里的时间类型为timestamp,
-
model结构体tag设置为 *time.Time
json:"activationTime" gorm:"type:timestamp;default:'null'"
-
默认存null
-
存前端传传来的时间戳时,按下面的代码处理
timeStart := time.Unix(paramData.Times[0]/1000, 0)
data.TimeStart = &timeStart
timeEnd := time.Unix(paramData.Times[1]/1000, 0)
data.TimeEnd = &timeEnd
表里的效果
前端post请求
页面效果:
前端post传参,传时间戳
{"cardNumber":2,"userLevel":2,"status":1,"times":[1587265284875,1595041284875]}
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
v-permisaction="['lbyttvipcard:lbyttvipcard:add']"
type="primary"
icon="el-icon-plus"
size="mini"
@click="handleAdd"
>新增
</el-button>
<!-- 添加或修改对话框 -->
<el-dialog :title="title" :visible.sync="open" width="500px">
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
<el-row>
<el-col :span="24">
<el-form-item label="使用时间" prop="times">
<el-date-picker
v-model="form.times"
type="daterange"
align="right"
unlink-panels
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
format="yyyy 年 MM 月 dd 日"
value-format="timestamp"
:picker-options="pickerOptions">
</el-date-picker>
</el-form-item>
</el-col>
</el-row>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
<script>
data() {
return {
lbyttvipcardList: [],
// 表单参数
form: {},
pickerOptions: {
shortcuts: [{
text: '最近一周',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近一个月',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近三个月',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
picker.$emit('pick', [start, end]);
}
}]
},
}
},
methods: {
/** 新增按钮操作 */
handleAdd() {
this.reset()
this.open = true
this.title = '添加会员卡激活码'
this.isEdit = false
},
/** 提交按钮 */
submitForm: function () {
this.$refs['form'].validate(valid => {
if (valid) {
if (this.form.id !== undefined) {
updateLbYttVipCard(this.form).then(response => {
if (response.code === 200) {
this.msgSuccess('修改成功')
this.open = false
this.getList()
} else {
this.msgError(response.msg)
}
})
} else {
addLbYttVipCard(this.form).then(response => {
if (response.code === 200) {
this.msgSuccess('新增成功')
this.open = false
this.getList()
} else {
this.msgError(response.msg)
}
})
}
}
})
},
}
</script>
go后台处理gin框架+gorm
type InsertLbYttVipCardParam struct {
CardNumber int `json:"cardNumber"`
UserLevel int `json:"userLevel"`
Times []int64 `json:"times"`
Status int `json:"status"`
}
func InsertLbYttVipCard(c *gin.Context) {
var paramData request.InsertLbYttVipCardParam
err := c.ShouldBindJSON(¶mData)
tools.HasError(err, "", 500)
//获取对应的商品
var goodsMod models.Goods
goodsMod.CateId = 4
goodsMod.SellerNote = tools.IntToString(paramData.UserLevel)
goodsDetail, _ := goodsMod.Get()
var data models.LbYttVipCard
data.UserLevel= paramData.UserLevel
data.CreateBy = tools.GetUserIdStr(c)
data.Status=paramData.Status
if len(paramData.Times) > 0 {
timeStart := time.Unix(paramData.Times[0]/1000, 0)
data.TimeStart = &timeStart
timeEnd := time.Unix(paramData.Times[1]/1000, 0)
data.TimeEnd = &timeEnd
}
for i := 0; i < paramData.CardNumber; i++ {
data.CardSn = fmt.Sprintf("VIP%d%s",data.UserLevel,GetRandomString(12))
data.Name = goodsDetail.GoodsName
data.GoodsSn = goodsDetail.GoodsSn
data.Create()
data.Id = 0
}
app.ResponseOK(c,"创建成功.")
}
//生成随机字符串
func GetRandomString(num int) string {
str := "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
bytes := []byte(str)
var result []byte
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < num; i++ {
result = append(result, bytes[r.Intn(len(bytes))])
}
return string(result)
}
go models里
package models
import (
"go-admin/global/orm"
"go-admin/tools"
"time"
_ "time"
)
type LbYttVipCard struct {
Id int `json:"id" gorm:"type:int(11);primary_key"` //
CardSn string `json:"cardSn" gorm:"type:int(11);"` // 激活码编号
Name string `json:"name" gorm:"type:varchar(128);"` // 会员卡名称
GoodsSn string `json:"goodsSn" gorm:"type:varchar(100);"` // 关连要goods表里的goods_sn
UserLevel int `json:"userLevel" gorm:"type:tinyint(1) unsigned;"` // 会员等级 1:体验会员 2:白银会员 3:黄金员会 4:铂金会员 5:黑金会员 6:钻石会员
ActivationUid int `json:"activationUid" gorm:"type:bigint(20);"` // 激活用户 关连lb_ytt_user表里的主键
ActivationTime *time.Time `json:"activationTime" gorm:"type:timestamp;default:'null'"` // 激活时间
CreateBy string `json:"createBy" gorm:"type:varchar(128);"` // 创建人 关连sys_user表里的主键
UpdateBy string `json:"updateBy" gorm:"type:varchar(128);"` // 修改人 关连sys_user表里的主键
IsUse int `json:"isUse" gorm:"type:tinyint(2) unsigned;"` // 是否使用 1:是 2:否
TimeStart *time.Time `json:"time_start" gorm:"type:timestamp;default:'null'"` // 有效期用开始时间
TimeEnd *time.Time `json:"time_end" gorm:"type:timestamp;default:'null'"` // 有效期结束时间
Status int `json:"status" gorm:"type:tinyint(1) unsigned;"` // 状态 1:正常 2:停用
DataScope string `json:"dataScope" gorm:"-"`
Params string `json:"params" gorm:"-"`
BaseModel2
DeletedAt *time.Time `sql:"index" json:"deletedAt"`
}
type BaseModel2 struct {
CreateTime int64 `json:"createTime"`
UpdateTime int64 `json:"updateTime"`
}
func (LbYttVipCard) TableName() string {
return "lb_ytt_vip_card"
}
// 创建LbYttVipCard
func (e *LbYttVipCard) Create() (LbYttVipCard, error) {
var doc LbYttVipCard
result := orm.Eloquent.Table(e.TableName()).Create(&e)
if result.Error != nil {
err := result.Error
return doc, err
}
doc = *e
return doc, nil
}
获取列表
后台返参
{
"code":200,
"data":{
"list":[
{
"id":1,
"cardSn":"VIP1NPY7QEFQH9CN",
"name":"体验会员",
"goodsSn":"yttvip001",
"userLevel":1,
"activationUid":100000156,
"activationTime":"2020-07-15T20:47:58+08:00",
"createBy":"1",
"updateBy":"1",
"isUse":1,
"time_start":"2020-07-14T17:36:03+08:00",
"time_end":"2021-07-14T17:36:10+08:00",
"status":1,
"dataScope":"",
"params":"",
"deletedAt":null,
"create_time":1594719428,
"update_time":1594719428,
"activationUidName":"",
"createByName":"admin"
}
],
"count":9,
"pageIndex":1,
"pageSize":10
},
"msg":""
}
页面渲染
<el-table-column label="激活时间" align="center" prop="activationTime" width="200">
<template slot-scope="scope">
<span>{{ parseTime(scope.row.activationTime) }}</span> #parseTime调用的element底层包里的函数把 2020-07-14T17:36:03+08:00 解析成 2020-07-14 17:36:03 08:00
</template>
</el-table-column>
<el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" width="160">
<template slot-scope="scope">
<span>{{ formatDate(scope.row.createTime) }}</span> #formatDate调用下面自己封闭的函数把时间戳解析成字符串
</template>
</el-table-column>
<script>
// 日期格式化 time=1551334252272; //定义一个时间戳变量 返回2020-6-20 08:06:50
export function formatDate(time) {
if (time.length === 0 || time === 0) {
return ""
}
let d=new Date(time*1000);
let timeObject = new Date(d); //创建一个指定的日期对象
let year = timeObject.getFullYear(); //取得4位数的年份
let month = timeObject.getMonth() + 1; //取得日期中的月份,其中0表示1月,11表示12月
let date = timeObject.getDate(); //返回日期月份中的天数(1到31)
let hour = timeObject.getHours(); //返回日期中的小时数(0到23)
let minute = timeObject.getMinutes(); //返回日期中的分钟数(0到59)
let second = timeObject.getSeconds(); //返回日期中的秒数(0到59)
return year + "-" + p(month) + "-"+ p(date) + " " + p(hour) + ":" + p(minute) + ":" + p(second);
}
//创建补0函数
function p(s) {
return s < 10 ? '0' + s: s;
}
</script>
页面效果: