question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Retrieve date(only) column as plain string without added time information (or custom type, in general)

See original GitHub issue

Problem

I’m having a date column in PostgreSQL. I.e. it only contains the date, no time, no timezone. In Prisma schema I have to define:

date         DateTime  @db.Date

In my API I only want to specify the date without time. I have to write a lot of nasty transformation, each time this column is read from or written to the database, e.g.

return await prisma.entity.findMany().map(e => ({ ...e, date: e.date.toISOString().substring(0,10) }))

Suggested solution

AFAIK there is no native “dateonly” type in Javascript. I’d really appreciate, if I could specify in the schema that this column should be handled as string:

date         String  @db.Date

Alternative: Transformer

An even more powerful alternative would be to allow transformers (e.g. using class-transformer) for each column to be specified, that are executed when transferring data from and to the database. This would allow users to have their columns transformed to the type they like to work with.

Alternative: Middleware

It was suggested (https://stackoverflow.com/questions/66109340/retrieve-dateonly-column-as-string-or-map-to-string-without-time-using-prisma) to use middlewares for this purpose. While this works in principle, it breaks the type checking. And the strong type checking is one of the biggest advantages of Prisma over alternative solutions. So, I don’t want to lose that.

Example:

    prisma.$use(async (params, next) => {
      if (
        params.model === 'Model' &&
        params.action === 'findMany'
      ) {
        const result = await next(params)
        result.forEach((element) => {
          if (element.date) {
            element.date = element.date.toISOString().substring(0, 10)
          }
        })
        return result
      }
      return next(params)
    })

prisma.model.findMany will still tell you the date property is Date while it actually is String. Also it is tedious to write transformation for all operations, where this model might be included. I’d prefer to declare this once for a column.

Additional context

This problem might be applicable to a wide range of column types where it would be nice to handle it in a different type than Prisma suggests. E.g. users could want to handle Datetime as instances of MomentJs or DayJs instead of native Date. Or they would like to handle Decimal as String or Number or BigJs. They might have custom implementations db.Xml, inet, cidr, …

Please let me know, if I should add more information etc. Or there are simple solutions, I might have missed 😃

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:25
  • Comments:6

github_iconTop GitHub Comments

24reactions
jhnnscommented, Sep 29, 2021

I think Prisma should completely avoid JavaScript’s native Date object and treat dates as regular strings (or at least Date ISO strings).

Converting dates to instances of Date sometimes adds unwanted precision:

new Date("2021-01-01").toISOString() // '2021-01-01T00:00:00.000Z'

2021-01-01 is timezone agnostic and carries a different date information than 2021-01-01T00:00:00.000Z

There are also other issues caused by this behavior: https://github.com/prisma/prisma/issues/7490 https://github.com/prisma/prisma/issues/4355

0reactions
jacobgoh101commented, Dec 2, 2022

On my end, this causes problems & confusion when parsing time in the browser.

I had to work around it by adding a Prisma middleware to sanitize the date values.

import { PrismaClient } from "@prisma/client";
import { formatISO } from "date-fns";
import { flatten, unflatten } from "flat";
import _ from "lodash";

export const prisma = new PrismaClient();

// Prisma middleware to sanitize date values
prisma.$use(async (params, next) => {
  let result = await next(params);

  if (_.isArray(result) || _.isObject(result))
    result = sanitizeDateValuesInObject(result);

  return result;
});

/**
 *
 * @param result any object
 * @returns object
 * This function remove problematic time component from date only values. It converts Date object to YYYY-MM-DD.
 * example of @db.Date column result 1995-05-17T00:00:00.000Z
 */
function sanitizeDateValuesInObject(result: any): any {
  if (_.isArray(result))
    return result.map((r) => sanitizeDateValuesInObject(r));
  if (!_.isObject(result)) return result;
  result = flatten(result);
  result = _.mapValues(result, (value, key) => {
    if (
      value instanceof Date &&
      value.toISOString().endsWith("T00:00:00.000Z")
    ) {
      return formatISO(value, { representation: "date" });
    }
    return value;
  });
  result = unflatten(result);
  return result;
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Convert dates stored as text to dates - Microsoft Support
Convert text dates with two-digit years by using Error Checking · Select the cell, cell range, or column that you want to reformat....
Read more >
6 Ways to Fix Dates Formatted as Text in Excel
6 ways to fix dates formatted ast text in Excel, plus a bonus technique using Power Query to fix various formats.
Read more >
Convert date to text in Excel - TEXT function and no-formula ...
Notepad automatically converts the dates to the text format. Press Ctrl+A to select all text strings, and then Ctrl+C to copy them. Switch...
Read more >
Demystifying DateTime Manipulation in JavaScript - Toptal
now() to directly get the time stamp without having to create a new Date object. Parsing a Date. Converting a string to a...
Read more >
Convert Date to Text in Excel - Explained with Examples
In this tutorial, you'll learn how to convert date to text in Excel. You can use the Text functions, text to column feature...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found