javascript neo4j-driver how to convert datetime into string

Viewed 723

I'm currently getting the error

'String cannot represent value: { year: { low: 2020, high: 0 }, month: { low: 7, high: 0 }, day: { low: 1, high: 0 }, hour: { low: 7, high: 0 }, minute: { low: 35, high: 0 }, second: { low: 45, high: 0 }, nanosecond: { low: 914000000, high: 0 }, timeZoneOffsetSeconds: { low: 0, high: 0 }, timeZoneId: null }'

which is caused by one of my properties being stored as datetime(). What would be the way to convert this into a string?

I am using the neo4j-driver from npm

2 Answers

This should work- addresses the two issues i commented on the accepted answer. Perhaps op already worked this out, but hopefully this will help somebody else.

import { DateTime } from 'neo4j-driver';

/**
 * Convert neo4j date objects in to a parsed javascript date object
 * @param dateString - the neo4j date object
 * @returns Date
 */
const parseDate = (neo4jDateTime: DateTime): Date => {
  const { year, month, day, hour, minute, second, nanosecond } = neo4jDateTime;

  const date = new Date(
    year.toInt(),
    month.toInt() - 1, // neo4j dates start at 1, js dates start at 0
    day.toInt(),
    hour.toInt(),
    minute.toInt(),
    second.toInt(),
    nanosecond.toInt() / 1000000 // js dates use milliseconds
  );

  return date;
};

console.log output to compare dates -

DateTime {
   year: Integer { low: 2021, high: 0 },
   month: Integer { low: 9, high: 0 },
   day: Integer { low: 6, high: 0 },
   hour: Integer { low: 15, high: 0 },
   minute: Integer { low: 41, high: 0 },
   second: Integer { low: 30, high: 0 },
   nanosecond: Integer { low: 184000000, high: 0 },
   timeZoneOffsetSeconds: Integer { low: 0, high: 0 },
   timeZoneId: null
 }
 2021-09-06T15:41:30.184Z

Since DateTime returns a bunch of neo4 int style stuff e.g.

DateTime {
  year: Integer { low: 2020, high: 0 },
  month: Integer { low: 7, high: 0 },
  day: Integer { low: 1, high: 0 },
  hour: Integer { low: 8, high: 0 },
  minute: Integer { low: 48, high: 0 },
  second: Integer { low: 18, high: 0 },
  nanosecond: Integer { low: 833000000, high: 0 },
  timeZoneOffsetSeconds: Integer { low: 0, high: 0 },
  timeZoneId: null
}

I am converting the field with .toString()

export function convertDateToString (
    date)
    : string {
        const date_values = [];
        for (const key in date) {
            const cursor = date[key];
            if (cursor) {
                date_values.push(cursor.toString());
            }
        }
        const the_date = new Date(...date_values as [number, number, number, number, number, number]);
        return the_date.toUTCString();
}
Related