Skip to content

Instantly share code, notes, and snippets.

@caixw
Created December 17, 2015 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caixw/d1f7681077da68f4ee1f to your computer and use it in GitHub Desktop.
Save caixw/d1f7681077da68f4ee1f to your computer and use it in GitHub Desktop.
通过golang将日期格式转换成unix时间戳,直接使用数据库内置函数,1970年之前的会被重置为零
// Copyright 2015 by caixw, All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package main
import (
"strings"
"time"
"github.com/issue9/orm"
"github.com/issue9/orm/dialect"
"github.com/issue9/orm/fetch"
_ "github.com/go-sql-driver/mysql"
)
func main() {
d := dialect.Mysql()
o, err := orm.NewDB("mysql", "root:@/yuesaopai", "", d)
if err != nil {
panic(err)
}
rows, err := o.Query(true, "select id,date from table")
if err != nil {
panic(err)
}
maps, err := fetch.MapString(false, rows)
rows.Close()
if err != nil {
panic(err)
}
for _, v := range maps {
/*years := v["date"][:4]
year, err := strconv.Atoi(years)
if err != nil {
panic(err)
}
if year > 1970 {
continue
}*/
// 假定字符串只有年月日,没有时间部分
datas := strings.Replace(v["date"], "/", "-", -1) + " 12:00:00"
t, err := time.Parse("2006-1-2 15:04:05", datas)
if err != nil {
panic(err)
}
sql := "update table set date=? where id=?"
_, err = o.Exec(true, sql, t.Unix(), v["id"])
if err != nil {
panic(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment