Skip to content

Instantly share code, notes, and snippets.

@sysnajar
Forked from narate/date_fmt.lua
Created May 25, 2018 13:42
Show Gist options
  • Save sysnajar/b8fd300de6568d5a421e4d7441259b0c to your computer and use it in GitHub Desktop.
Save sysnajar/b8fd300de6568d5a421e4d7441259b0c to your computer and use it in GitHub Desktop.
OpenResty (ngx_lua) MongoDB ISODate()
local mongol = require "resty.mongol"
local bson = require "resty.mongol.bson"
local conn = mongol:new()
conn:set_timeout(1000)
local ok, err = conn:connect('127.0.0.1', '27017')
if not ok then
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say('Failed : '.. err)
ngx.exit(ngx.status)
end
local ngx_now = ngx.now()
local now = bson.get_utc_date(ngx_now * 1000)
local db = conn:new_db_handle('test')
local col = db:get_col('users')
local doc = { createdAt = now, username = 'test', password = ngx.md5('123456') }
ok, err = col:insert({doc}, true, true)
if not ok then
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say('Failed : '.. err)
ngx.exit(ngx.status)
end
local date_fmt = string.format('!%%Y-%%m-%%dT%%T.%03dZ', now.v % 1000)
ngx.say(os.date(date_fmt, now.v/1000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment