0

tl;dr - How do I access and modify the properties of a DateTime object in LWC?

I'm trying to create code that will populate an HTML field with the current date-time, adn the current date-time plus 30 minutes. My current code is as follows:

Javascript

import { LightningElement, wire } from 'lwc';
import getNowPlusThirty from '@salesforce/apex/MeetingMakerUtil.getNowPlusThirty';

export default class findingNow extends LightningElement {

    now = Date.now();

    @wire(getNowPlusThirty)
    endDateTime;

}

Apex

@AuraEnabled(cacheable=true)
public static Datetime getNowPlusThirty(){
    return system.now().addMinutes(30);
}

HTML

<template>
  <p>Datetime: --|{now}|--</p>
  <p>EndTime: --|{endDateTime}|--</p>
</template>

The results render as follows:

  • Datetime results in something like this: Now: 1583535981831
  • EndTime results in this: EndTime: --|object Object|--

I need to know how to modify the serial code 1583535981831 to get things like year and time formatting, and the dateTime object object Object in the same way. My attempts at using normal javascript formatting such as Date.now().format('MM/DD/YYYY h:mm a') have simply thrown errors.

1
  • You could just do it all in js: var d = new Date(); d.setMinutes(d.getMinutes() + 30); Mar 6, 2020 at 23:47

2 Answers 2

5

LWC doesn't track the internals of properties of certain objects, like Date.

https://developer.salesforce.com/docs/component-library/documentation/en/48.0/lwc/lwc.reactivity_data_types

You'll need to output the value as a string and assign it to a property.

As for the the other issue, try replacing:

<p>EndTime: --|{endDateTime}|--</p> with <p>EndTime: --|{endDateTime.data}|--</p>

1
  • Thanks Ben. endDateTime.data did the trick
    – Jwok
    Mar 7, 2020 at 0:34
5

You can use lightning-formatted-date-time, as in:

<lightning-formatted-date-time value={now}></lightning-formatted-date-time>

Or you can use a getter to format this:

get nowFormatted {
    return now.toLocaleString(); 
}

To get thirty minutes from now, you can just add it to the existing value:

get nowPlusThirtyFormatted() {
    let nowPlusThirty = new Date();
    nowPlusThirty.setMinutes(nowPlusThirty.getMinutes()+30);
    nowPlusThirty = new Date(nowPlusThirty);
    return nowPlusThirty;
}

For your wire property, remember that it returns an object with two properties. In your example, {endDateTime.data} contains the actual DateTime value.


Side note: Don't use a @wire like this, since it won't be updated until the cache expires for that Apex call, which will cause issues. cacheable=true is meant to be used for idempotent calls (i.e. the same method called with the same parameters should produce the same output each time). You'll be off by a few minutes until/unless the cache decides to expire.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .