Home > other >  How to change the String date to TimeStamp in Node.js?
How to change the String date to TimeStamp in Node.js?

Time:09-25

Below is my Node.js code running in my REST API. It gets the data from a database and return to the caller application.

const mysql = require('mysql2');
const errorCodes = require('source/error-codes');
const PropertiesReader = require('properties-reader');

const prop = PropertiesReader('properties.properties');

const con = mysql.createConnection({
  host: prop.get('server.host'),
  user: prop.get("server.username"),
  password: prop.get("server.password"),
  port: prop.get("server.port"),
  database: prop.get("server.dbname")
});


exports.getUserByID = (event, context, callback) => {

  const params = event.queryStringParameters;


  if (!params || params.id == null) {
    context.callbackWaitsForEmptyEventLoop = false;
    var response = errorCodes.missing_parameters;
    callback(null, response)
  }
  else {
    const { id } = event.queryStringParameters;
    console.log("id", id);
    //log.console("id",id);

    // allows for using callbacks as finish/error-handlers
    context.callbackWaitsForEmptyEventLoop = false;
    const sql = "select * from user where iduser = ?";
    con.execute(sql, [id], function (err, result) {
      if (err) {
        console.log(err);
        var response = errorCodes.internal_server_error;
        callback(null, response);
      }
      else {
        var response = {
          "statusCode": 200,
          "headers": {
            "Content-Type": "application/json"
          },
          "body": JSON.stringify(result),
          "isBase64Encoded": false
        };
        callback(null, response)
      }
    });
  }
};

This gives the following output. It is a JSON Array.

[
    {
        "iduser": 2,
        "first_name": "John",
        "last_name": "Vector",
        "profile_picture": "https://link",
        "email": "[email protected]",
        "phone": "0000000000",
        "is_disabled": 0,
        "created_date": "2021-07-28T00:00:00.000Z",
        "last_updated": "2021-07-28T00:00:00.000Z",
        "uid": "2"
    }
]

The caller app accepts the created_date and last_updated fields as TimeStamps so the field data type needs to be int. For your information, the caller app is a Flutter app and its model class looks like this.

import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';

    @JsonSerializable()
    class User {
      int? idUser;
      String? uid;
      String? firstName;
      String? lastName;
      String? profilePicture;
      String? email;
      String? phone;
      int? isDisabled;
      int? createdDate;
      int? lastUpdated;
    
      User(
          {this.idUser,
          this.uid,
          this.firstName,
          this.lastName,
          this.profilePicture,
          this.email,
          this.isDisabled,
          this.createdDate,
          this.lastUpdated,
          this.phone});
    
      factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
    
      Map<String, dynamic> toJson() => _$UserToJson(this);
    }

My question is, from my Node.JS code, how can I return the same result only with created_date and last_updated changed as TimeStamp of type int ?

CodePudding user response:

Excuse me if I didn't understand your need, but why don't you simply get the time of this well-recognized date format ?

new Date("2021-07-28T00:00:00.000Z").getTime()

seems ok.

CodePudding user response:

You can map over your JSON Array and convert dates to timestamp.

const convertToTimestamp = function (date) {
  return new Date(date).getTime()
}

const reformattedOutput = array.map((item) => {
  return {
    ...item,
    "created_date": convertToTimestamp(item.created_date),
    "last_updated": convertToTimestamp(item.last_updated)
  }
})

CodePudding user response:

MySQL is a string based protocol. If you want to always convert a date string into something else, you can use a typeCast and conditionally change the value.

Here is an example of a typecast I just found:

const db = mysql.createConnection({
    typeCast: function (field, next) {
        if (field.type == 'DATE') {
            return field.string();
        }
        return next();
    }
})
  • Related