Created
December 17, 2015 14:26
-
-
Save caixw/d1f7681077da68f4ee1f to your computer and use it in GitHub Desktop.
通过golang将日期格式转换成unix时间戳,直接使用数据库内置函数,1970年之前的会被重置为零
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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