0

I want to display time in 3 different formats, along side follow the translation strategy as well. That is if user selects to translate the page, user should be able to see the date in his/her local translated with selected time format method.

  1. To display date in ISO format => 2010-01-19T14:32:35+03:00
  2. To display Date along with Time zone => January 31, 2010, 14:32 (UTC+3:30)
  3. To display date in respect to when the record is created like => 5 hours ago, 2 minutes ago

So I have this method in my JS file of LWC to update these date time format.

dateFormat(){
    if(this.myTaskWrappers) {
        this.myTaskWrappers = this.myTaskWrappers.map(item => {
            if(item.Due_Date__c){
                // console.log('DATE FORMAT')
                let dateobj = new Date(item.Due_Date__c); 

                if(this.updatedTimeFormat === 'ISO'){
                    this.isoDate = dateobj.toISOString();
                    item.Due_Date__c = this.isoDate;
                    console.log('this.isoDate '+this.isoDate); // 2023-06-29T18:30:00.000Z
                    let isoDateConvert= new Date(this.isoDate);
                    console.log('isoDateConvert '+isoDateConvert);

                }
                else if(this.updatedTimeFormat === 'Absolute'){
                    this.absoluteDate= dateobj.toString();
                    console.log('this.absoluteDate '+this.absoluteDate); // Fri Jun 30 2023 00:00:00 GMT+0530 (India Standard Time)
                    item.Due_Date__c = this.absoluteDate;
                }
                else{
                    let dueDateInstance = new Intl.DateTimeFormat(LOCALE,
                        {   year: 'numeric',
                            month: 'long',
                            day: 'numeric'
                        }).format(dateobj);
                    item.Due_Date__c = dueDateInstance;
                }

            }
            return item;
            });
            
    }
}
  1. ISO formatting is correct, my doubt is for +3:00 is always showing .000z
  2. For 2nd time format i.e. 'Absolute', converted time is coming up with DAY and month I want to have in full format. How to achieve the same format which mentioned in above 2nd point.
  3. For 3rd formatting, logic is not sorted yet in my mind. Any suggestions are welcome.

Please let me know if any other reference of code is needed.

1
  • Questions cannot be "hidden" on this site. There is no such feature.
    – Adrian Larson
    Aug 17, 2023 at 1:28

1 Answer 1

0

The timezone returned by toISOString() is always UTC. I would keep it.

For the Absolute time you could leverage Intl.DateTimeFormat with an appropriate option object, e.g.:

const dueDate = new Date(2010, 0, 31, 14, 32);
const hour12 = true; // Turn this to false if you want to have 24-hour time
const absoluteOptions = { 
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    hour12,
    timeZoneName: 'short'
};
const absoluteTimeFormat = new Intl.DateTimeFormat('en-US', absoluteOptions); // en-US to have month first
console.log(absoluteTimeFormat.format(dueDate)); // January 31, 2010 at 14:32 GMT+1
// to remove "at" you could leverage replace()
console.log(absoluteTimeFormat.format(dueDate).replace(' at ', ' ')); // January 31, 2010 2:32 PM GMT+1

The option object has a hour12 property to let you switch between 12-hour (if true) and 24-hour (if false) time format, so it's true you would get 2:32 PM, while if it's false you would get 14:32.
I used replace() method to remove at from that string, but I advice against heavy string manipulation.

To display the difference between CreatedDate and Due_Date__c, once you have both Date object, you can create a third one for the difference, then extract its milliseconds calling getTime() and using them to calculate hours and minutes:

const dueDate = new Date(2010, 0, 31, 14, 32);
const createdDate = new Date(2010, 0, 31, 13, 30);
const diffDate = new Date(dueDate.getTime() - createdDate.getTime());
let seconds = diffDate.getTime() / 1000;

const hours = Math.floor(seconds / 3600); // calling Math.floor to get an integer value

seconds -= hours * 3600;

const minutes = Math.floor(seconds / 60);

let diffString = `${minutes} minutes ago`;
if (hours > 0) {
  diffString = `${hours} hours ago, ${diffString}`;
}
console.log(diffString);

The dateFormat method should look like:

dateFormat() {
    if (this.myTaskWrappers) {
        this.myTaskWrappers = this.myTaskWrappers.map((item) => {
            if (item.Due_Date__c) {
                const dueDate = new Date(item.Due_Date__c); 

                if (this.updatedTimeFormat === 'ISO') {
                    this.isoDate = dueDate.toISOString();
                    item.Due_Date__c = this.isoDate;
                    console.log('this.isoDate '+this.isoDate); // 2023-06-29T18:30:00.000Z
                }
                else if (this.updatedTimeFormat === 'Absolute') {
                    // Since Due_Date__c is just a Date, not a Datetime, we don't need hours, minutes and seconds
                    const absoluteOptions = { 
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric'
                    };
                    const absoluteTimeFormat = new Intl.DateTimeFormat('en-US', absoluteOptions); // en-US to have month first
                    this.absoluteDate = absoluteTimeFormat.format(dueDate);
                    console.log('this.absoluteDate', this.absoluteDate);
                    item.Due_Date__c = this.absoluteDate;
                }
                else {
                    const createdDate = new Date(item.CreatedDate); // Assuming that CreatedDate has been retrieved
                    const diffDate = new Date(dueDate.getTime() - createdDate.getTime());
                    let seconds = diffDate.getTime() / 1000;

                    const secondsInAnHour = 3600;
                    const secondsInADay = secondsInAnHour * 24;
                    const secondsInAMonth = secondsInADay * 30;
                    const secondsInAYear = secondsInADay * 365;
                    
                    const years = Math.floor(seconds / secondsInAYear); 
                    seconds -= years * secondsInAYear;
                    
                    const months = Math.floor(seconds / secondsInAMonth);
                    seconds -= months * secondsInAMonth;
                    
                    const days = Math.floor(seconds / secondsInADay);
                    seconds -= days * secondsInADay;

                    const hours = Math.floor(seconds / secondsInAnHour); 
                    seconds -= hours * secondsInAnHour;

                    const minutes = Math.floor(seconds / 60);

                    let diffString = `${minutes} minutes ago`;
                    if (hours > 0) {
                      diffString = `${hours} hours ago, ${diffString}`;
                    }
                    if (days > 0) {
                      diffString = `${days} days ago, ${diffString}`;
                    }
                    if (months > 0) {
                      diffString = `${months} months ago, ${diffString}`;
                    }
                    if (years > 0) {
                      diffString = `${years} years ago, ${diffString}`;
                    }
                    console.log('CreatedDate - DueDate:', diffString);
                    item.Due_Date__c = diffString;
                }

            }
            return item;
        });
    }
}
11
  • thanks for this help. I am doing ABSOLUTE one first, so what I could notice, it is always showing me time as 24:00 hrs... as for 12:00 AM. What could be the reason and how to update it. Plus I want to remove the 'at' from 'January 31, 2010 at 14:32 GMT+1' and add 'GMT+1' in brackets. Can I do it using string methods and modify it.
    – SF Learner
    Aug 11, 2023 at 11:53
  • The more you mess with strings the harder it is for you to support multi-language orgs. You may not need to now, but it is possible you might in the end. In javascript, use a library that supports localisation, like luxon.
    – Phil W
    Aug 11, 2023 at 12:00
  • @SFLearner to switch between 24 or 12-hours time format you could set hour12 property, I edited the answer to show it and to remove at from that string, but as Phil said, usually isn't wise messing too much with strings. Anyway replace() and substring() methods may meet your needs.
    – RubenDG
    Aug 11, 2023 at 12:15
  • Thanks @PhilW and RubenDG. I understand. However, even if I am setting hour12 property to true or false it is showing me time as 12:00 AM and 24:00 only respectively. Not the real time.
    – SF Learner
    Aug 11, 2023 at 12:24
  • @SFLearner sorry, but I didn't get it, could you please elaborate or provide an example? If you run the code I posted in the browser's console, you'll see 14:32 if hour12 is false and 2:32 PM if true.
    – RubenDG
    Aug 11, 2023 at 12:32

You must log in to answer this question.

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