Change date and format in Js

my code is working perfect but I want it to accept YYYY-MM-DD HH:mm:ss format when I write in the console as console.log(fromNow('19-09-2022 22:27:10')) but it returns undefined, otherwise when I am writing in YYYY-MM-DD it is working perfectly.

how do I fix this issue ?

function fromNow(date, nowDate = Date.now(), rft = new Intl.RelativeTimeFormat(undefined, { numeric: "auto" })) {
    const SECOND = 1000;
    const MINUTE = 60 * SECOND;
    const HOUR = 60 * MINUTE;
    const DAY = 24 * HOUR;
    const WEEK = 7 * DAY;
    const MONTH = 30 * DAY;
    const YEAR = 365 * DAY;
    const intervals = [
        { ge: YEAR, divisor: YEAR, unit: 'year' },
        { ge: MONTH, divisor: MONTH, unit: 'month' },
        { ge: WEEK, divisor: WEEK, unit: 'week' },
        { ge: DAY, divisor: DAY, unit: 'day' },
        { ge: HOUR, divisor: HOUR, unit: 'hour' },
        { ge: MINUTE, divisor: MINUTE, unit: 'minute' },
        { ge: 30 * SECOND, divisor: SECOND, unit: 'seconds' },
        { ge: 0, divisor: 1, text: 'just now' },
    ];
    const now = typeof nowDate === 'object' ? nowDate.getTime() : new Date(nowDate).getTime();
    const diff = now - (typeof date === 'object' ? date : new Date(date)).getTime();
    const diffAbs = Math.abs(diff);
    for (const interval of intervals) {
        if (diffAbs >= interval.ge) {
            const x = Math.round(Math.abs(diff) / interval.divisor);
            const isFuture = diff < 0;
            return interval.unit ? rft.format(isFuture ? x : -x, interval.unit) : interval.text;
        }
    }
}
console.log(fromNow('2022-09-19 22:27:10'))

The problem is that new Date(date) cannot accept ‘19-09-2022 22:27:10’ as a date.

Because new Date() works well when it’s only a date without time, I recommend that you use the split method to separate the input into both a date and a time, create a date object only from the date, then add on the time.

sir, could you please share with me the snippet of how I do this, I don’t know I do this, I also find this split method on google to find similar but not achieve the goal.

Let’s start from the date that’s not working for you. "19-09-2022 22:27:10"

Currently when doing new Date(“19-09-2022 22:27:10”) we get Invalid Date
Even when using new Date(“19-09-2022”) we still get Invalid Date because the date format is not acceptable.

We need to do more than just split apart the date and time. We need to extract out all of the relevant information, and use the Date object to set them separately.

function createDate(dateString) {
    const dateRx = /(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/;
    const [dd, mm, yyyy, hour, min, sec] = dateString.match(dateRx);
    const date = new Date();
    date.setDate(dd);
    date.setMonth(mm - 1); // zero-based number
    date.setYear(yyyy);
    date.setHours(hour);
    date.setMinutes(min);
    date.setSeconds(sec);
    return date;
}

now in your code instead of using new Date(date) you can use createDate(date) instead.

For the record, new Date can gladly accept “09/19/2022 22:27:10”.

19-09-2022 22:27:10 is not the format you specified at the top of your post:

new Date() will also happily accept “2022-09-19 22:27:10”.

MM-DD-YYYY is not a valid javascript format for a date. It’s got nothing to do with the time bit.

That’s why extra work is needed to accommodate that requirement, which has been achieved in the previous post.

One day we’ll all agree on a standard and the whole world will use Stardates. But until then, the work toils on… :wink:

Thanks for helping me out as well. :slight_smile:

I run this code but it was not working and showed the wrong details as live code here https://playcode.io/972919
Please help me, with how to make this correct where if will calculate with time and without time also with this pattern (DD-MM-YYYY HH:mm:ss)

Please provide details about all of the date patterns that you need it to support.

DD-MM-YYYY,
YYYY-MM-DD,
DD-MM-YYYY HH:mm:ss,
YYYY-MM-DD HH:mm:ss

Paul, arent you missing the Whole-String match at index 0 here?

This does appear to fix it

const [dd, mm, yyyy, hour, min, sec] = dateString.match(dateRx).slice(1);
// or
const [fullmatch, dd, mm, yyyy, hour, min, sec] = dateString.match(dateRx);
1 Like

Thank you for those date format requirements.

Here’s some code that is capable of supporting all of those different types of formats.

// usage: const dmyhms = getDateTime("30-09-2022 13:14:15");
// result: {day: 30, month: 9, year: 2022, hour: 13, month: 14, second: 15}

function getDmyDate(datetimestring) {
    const dateRx = /(\d+)-(\d+)-(\d+)/;
    const match = datetimestring.match(dateRx);
    if (!match) {
        return {};
    }
    const [day, month, year] = match.slice(1);
    return {
        day: Number(day),
        month: Number(month),
        year: Number(year)
    };
}
function getYmdDate(datetimestring) {
    const dateRx = /(\d+)-(\d+)-(\d+)/;
    const match = datetimestring.match(dateRx);
    if (!match) {
        return {};
    }
    const [year, month, day] = match.slice(1);
    return {
        year: Number(year),
        month: Number(month),
        day: Number(day)
    };
}
function getTime(datetimestring) {
    const timeRx = /(\d+):(\d+):(\d+)/;
    const match = datetimestring.match(timeRx);
    if (!match) {
        return {hour: 0, minute: 0, second: 0};
    }
    const [hour, minute, second] = match.slice(1);
    return {
        hour: Number(hour),
        minute: Number(minute),
        second: Number(second)
    };
}
function getDateTime(datetimestring) {
  const datetime = {};
  if (datetimestring.substr(1, 1) === "-" ||
      datetimestring.substr(2, 1) === "-") {
      const date = getDmyDate(datetimestring);
      Object.assign(datetime, date);
  } else {
      Object.assign(datetime, getYmdDate(datetimestring));
  }
  Object.assign(datetime, getTime(datetimestring));
  return datetime;
}

The code can be found at https://jsfiddle.net/8hkqnyc2/

You can then combine that with a slightly modified createDate() function:

function createDate(dateObj) {
    const date = new Date();
    date.setDate(day);
    date.setMonth(month - 1); // zero-based number
    date.setYear(year);
    date.setHours(hour);
    date.setMinutes(minute);
    date.setSeconds(second);
    return date;
}
...
const dmyhms = getDateTime(date);
const diff = now - (typeof date === 'object' ? date : createDate(dmyhms).getTime();

I really do not understand How your code will be set inside my code. thank you so much that you spend your precious time on the thread but last help on this please set your code in my below code and help me find the expected output.

It will be done by replacing the const diff line with the two bottom lines from my previous post.

Those two lines use getDateTime() and all of the code from post #14, and the createDate() function from post #15.