· 6 years ago · Mar 15, 2019, 04:30 AM
1const D = require('date-fns')
2const Mysql = require('mysql')
3
4database = 'Hr'
5
6run().catch((err) => console.error(err))
7
8async function run() {
9 const conn = Mysql.createConnection({
10 host: 'localhost',
11 user: 'root',
12 password: 'example',
13 database,
14 charset: 'utf8mb4',
15 })
16
17 const table = 'date_test'
18
19 await query(conn, `DROP TABLE IF EXISTS ??`, table)
20 await query(
21 conn,
22 `
23 CREATE TABLE IF NOT EXISTS ?? (
24 d DATETIME NOT NULL,
25 ts TIMESTAMP NOT NULL
26 )`,
27 table
28 )
29
30 const ts1 = Date.now()
31
32 console.log('ts1 :', ts1)
33 console.log('ts1 date :', new Date(ts1))
34 console.log('ts1 locale :', D.format(new Date(ts1), 'yyyy-MM-dd hh:mm:ss'))
35
36 await query(conn, 'INSERT INTO ?? SET d = ?, ts = ?', table, new Date(ts1), new Date(ts1))
37
38 const res = await query(conn, 'SELECT * FROM ??', table)
39 const { d, ts } = res[0]
40
41 console.log('d :', d, 'type:', typeof d)
42 console.log('ts :', ts, 'type:', typeof ts)
43 console.log('d locale :', D.format(d, 'yyyy-MM-dd hh:mm:ss'))
44 console.log('ts locale :', D.format(ts, 'yyyy-MM-dd hh:mm:ss'))
45
46 // This prints:
47 //
48 // ts1 : 1552262777999
49 // ts1 date : 2019-03-11T00:06:17.999Z
50 // ts1 locale : 2019-03-11 09:06:17
51 // d : 2019-03-11T00:06:18.000Z type: object
52 // ts : 2019-03-11T00:06:18.000Z type: object
53 // d locale : 2019-03-11 09:06:18
54 // ts locale : 2019-03-11 09:06:18
55
56 conn.end()
57}
58
59function query(conn, sql, ...rest) {
60 return new Promise((resolve, reject) => {
61 conn.query(sql, [...rest], (error, results) => {
62 if (error) {
63 reject(error)
64 return
65 }
66 resolve(results)
67 })
68 })
69}