首页 > 解决方案 > 我如何在没有任何库的情况下使用 javascript 创建一个带有时区的日期来保存到 postgres

问题描述

我正在尝试将带有时区的日期保存到我的 postgress 数据库中。使用时出现以下错误created_at = Date.now()

{"errors":[{"extensions":{"path":"$.selectionSet.insert_users.args.objects","code":"data-exception"},"message":"date/time field value out of range: \"1588130621916\""}]}

这是代码,我将 asterix 放在与问题无关的代码上。

function (user, context, callback) {
  const userId = user.user_id;
  const email = user.email;
  let name;
  const created_at = Date.now();
  console.log(created_at);

  if (user.name) {
    name = user.name;
  } else {
    name = user.user_metadata.full_name;
  }

  const admin_secret = "********";
  const url = "*******/v1/graphql";
  request.post({
      headers: {'content-type' : 'application/json', 'x-hasura-admin-secret': admin_secret},
      url:   url,
      body:    `{\"query\":\"mutation($id: String!, $name: String, $created_at: timestamptz!, $email: String!) {\\n          insert_users(\\n            objects: [{ id: $id, name: $name, created_at: $created_at, email: $email, username: $id }]\\n            on_conflict: {\\n              constraint: users_pkey\\n              update_columns: [updated_at, name]\\n            }\\n          ) {\\n            affected_rows\\n          }\\n        }\",\"variables\":{\"id\":\"${userId}\",\"name\":\"${name}\", \"created_at\":\"${created_at}\",\"email\":\"${email}\"}}`
  }, function(error, response, body){
       console.log(body);
       callback(null, user, context);
  });
}

标签: postgresqlgraphqlhasura

解决方案


Te sugeriria revisar que la columna en la base de datos soporte el dato de tipo fecha con time-zone ej mycolumn TIME with time-zone

Lo segundo seria chequear como recive el formato de hora tu end-point ejemlo 2012-04-23T18:25:43.511Z es el formato de fecha que se envia en un json。

const jsondate = JSON.stringify(new Date());//javascript-format


推荐阅读