Can I customize timestamp data?

default discord avatar
ericuldalllast year
1 3

I'm integrating payload into an already active data model.

The good:
We already use createdAt and updatedAt as our timestamp fields

The Bad:
We store them as an integer rather than a Date object

Is there some way to change payload defaults to read/write those as integers?

  • Selected Answer
    default discord avatar
    ericuldalllast year

    I got it working!

    import { Field } from 'payload/types';
    
    const CreatedAt: Field = {
      name: 'createdAt',
      type: 'number',
      admin: {
        disabled: true,
      },
      hooks: {
        beforeChange: [(args) => {
          if (args.operation == 'create') {
            return (new Date).getTime();
          }
        }]
      }
    }
    
    export default CreatedAt;
    
    3 replies
  • discord user avatar
    JarrodMFlesch
    last year

    Nice work @ericuldall, way to keep after it 👊 you can override updatedAt, createdAt and id if you provide your own fields with the same names - like you found out.

  • discord user avatar
    JarrodMFlesch
    last year

    Also - are you in our discord? You should totally join, we're an active bunch over there: https://discord.com/invite/payload

  • default discord avatar
    ericuldalllast year

    I'll join up. Thanks!

  • default discord avatar
    ericuldalllast year

    UPDATE:
    It looks like the CMS reads my timestamps fine, but I need a way to override the Date object when creating/updating documents from inside of the CMS.

    Looking at global hooks, does that seem like the way?

    Can't find docs on where to implement global hooks. Any helps is appreciated.

  • default discord avatar
    ericuldalllast year

    Now trying a custom field with field hooks like so:

    import { Field } from 'payload/types';
    
    const CreatedAt: Field = {
      name: 'createdAt',
      type: 'date',
      admin: {
        date: {
          pickerAppearance: 'dayAndTime'
        }
      },
      hooks: {
        afterRead: [(args) => {
          return new Date(args.value);
        }],
        beforeChange: [(args) => {
          return (new Date(args.value)).getTime();
        }],
        afterChange: [(args) => {
          return new Date(args.value);
        }]
      }
    }
    
    export default CreatedAt;
    

    So this is pretty cool and almost works. I get the date rendered in a date field in the object (i'll probably hide it later), but when I save I get an error complaining about it being a number, but from my understanding it should pass validation before I convert it to a number in the beforeChange hook.

    Any idea why that happens?

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.