You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

报错toStandardDate不是函数:如何在TypeScript中正确使用Neo4j的DateTime?

问题

我尝试了两种导入方式:

// I've tried both imports
import { DateTime } from "neo4j-driver";
//import {DateTime} from 'neo4j-driver-core/lib/temporal-types.js'

export type LABELLED = Relationship<
  Integer,
  {
    created: DateTime;
  }
>;

// 后续使用代码:
created: pageResult.r.properties.created.toStandardDate().toDateString(),

运行时触发错误:

TypeError: pageResult.r.properties.created.toStandardDate is not a function

解决建议
  • 先确认运行时数据类型:打印pageResult.r.properties.created的typeof和constructor.name,大概率它是原生JS Date对象或ISO时间字符串,而非neo4j-driver封装的DateTime实例——因为neo4j驱动默认会自动把Temporal类型转换为原生JS类型。
  • 若要保留neo4j DateTime实例:创建驱动时添加配置禁用自动转换(以v5+为例):
    import neo4j from 'neo4j-driver';
    const driver = neo4j.driver(URI, neo4j.auth.basic(USER, PASSWORD), {
      transformers: {
        fromDb: {
          DateTime: val => val // 不转换,保留驱动原生DateTime实例
        }
      }
    });
    
    配置后返回的created就是neo4j DateTime实例,即可正常调用toStandardDate()。
  • 若无需neo4j DateTime实例:直接用原生JS处理:
    • 若返回的是Date对象:直接调用toDateString()即可,无需toStandardDate()
      created: pageResult.r.properties.created.toDateString(),
      
    • 若返回的是ISO字符串:先转为Date对象再处理
      created: new Date(pageResult.r.properties.created).toDateString(),
      
  • 同步TypeScript类型定义:如果运行时拿到的是原生Date或字符串,要修改类型定义匹配实际数据:
    export type LABELLED = Relationship<
      Integer,
      {
        created: Date; // 或 string(如果是ISO字符串)
      }
    >;
    

内容的提问来源于stack exchange,提问作者Kasper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:15:13