Steps for incorporating "about minutes ago, about hours ago, etc;" into a .filter for an Angular/Ionic v1 project

Can someone help me figure out how to incorporate phrases like "from now," "ago," etc. into a JS filter in my ionic v1 project for WordPress without using UTC Date?

I am currently working on an Ionic v1 app that is native to WordPress, so it's crucial for me to accurately display the date of each post within the app.

Displaying dates in UTC format is too lengthy for my liking; I prefer to show them as (1 hour ago, year, etc.) only! Thank you.

Here is the code snippet I am using:

.filter('timeAgo', function(){
return function timeAgo(time){
    switch (typeof time) {
        case 'number':
          break;
        case 'string':
          time = +new Date(time);
          break;
        case 'object':
          if (time.constructor === Date) time = time.getTime();
          break;
        default:
          time = +new Date();
      }
      var time_formats = [
        [60, 'seconds', 1], // 60
        [120, '1 minute ago', '1 minute from now'], // 60*2
        [3600, 'minutes', 60], // 60*60, 60
        [7200, '1 hour ago', '1 hour from now'], // 60*60*2
        [86400, 'hours', 3600], // 60*60*24, 60*60
        [172800, 'Yesterday', 'Tomorrow'], // 60*60*24*2
        [604800, 'days', 86400], // 60*60*24*7, 60*60*24
        [1209600, 'Last week', 'Next week'], // 60*60*24*7*4*2
        [2419200, 'weeks', 604800], // 60*60*24*7*4, 60*60*24*7
        [4838400, 'Last month', 'Next month'], // 60*60*24*7*4*2
        [29030400, 'months', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4
        [58060800, 'Last year', 'Next year'], // 60*60*24*7*4*12*2
        [2903040000, 'years', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12
        [5806080000, 'Last century', 'Next century'], // 60*60*24*7*4*12*100*2
        [58060800000, 'centuries', 2903040000] // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100
      ];
      var seconds = (+new Date() - time) / 1000,
        token = 'ago',
        list_choice = 1;
    
      if (seconds == 0) {
        return 'Just now'
      }
      if (seconds < 0) {
        seconds = Math.abs(seconds);
        token = 'from now';
        list_choice = 2;
      }
      var i = 0,
        format;
      while (format = time_formats[i++])
        if (seconds < format[0]) {
          if (typeof format[2] == 'string')
            return format[list_choice];
          else
            return Math.floor(seconds / format[2]) + ' ' + format[1] + ' ' + token;
        }
      return time;
    }
    
    var aDay = 24 * 60 * 60 * 1000;
    console.log(time_ago(new Date(Date.now() - aDay)));
    console.log(time_ago(new Date(Date.now() - aDay * 2)));
    
}

Could someone please review my code and point out any mistakes or errors?

Answer №1

If you want to utilize day.js, check out the following references: and

dayjs.extend(window.dayjs_plugin_relativeTime)

console.log(dayjs().to(dayjs('2000-01-01'))); //for years ago

console.log(dayjs().to(dayjs(new Date("2022-07-13T04:15:39.497Z")))); //for months ago

console.log(dayjs().to(dayjs(new Date("2022-09-13T04:15:39.497Z")))); //for days ago

console.log(dayjs().to(dayjs(new Date("2022-09-15T03:15:39.497Z")))); //for hours ago

console.log(dayjs().to(dayjs(new Date("2022-09-15T04:15:39.497Z")))); //for minutes ago

console.log(dayjs().toNow()); //for seconds ago
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/relativeTime.js">
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Warning: An unhandled promise error occurred due to a validation error

I've been facing an issue for the past few days. Currently, I'm diving into learning the MEAN stack, but while trying to create a user on MongoDB using Mongoose schema, I encountered this problem: (node:93337) UnhandledPromiseRejectionWarning: ...

"Enhance Your Browse experience: Chrome Extension that automatically appends content to pages

I'm currently developing a Chrome extension that detects when a URL on a specific domain changes, and if the URL matches a certain pattern, it will add new HTML content to the webpage. Here is an excerpt from my manifest.json file: { "name": "Ap ...

What is the process for incorporating beforeAnimate and afterAnimate callbacks into a custom jQuery plugin?

Let's imagine I have developed a plugin: // creating the plugin (function($){ $.fn.myPlugIn = function(options){ defaults = { beforeAnimate : function(){}, afterAnimate : function(){} ...

What is the process to designate a specific value to a key in an array?

I need assistance in updating the description array within the schema by adding the about and link values, followed by using the .save() function to store it in the database. Any guidance on this issue would be greatly appreciated. Thank you for your help. ...

What is the best way to determine the moving average of an Object value within an array?

In my dataset, I have an array called 'scores' that contains 4 objects. export const scores = [ { day: '1', Barcelona: 1, Real: 3, Valencia: 0}, { day: '2', Barcelona: 4, Real: 6, Valencia: 3}, { day: '3', Bar ...

Using AJAX to inject JSON data from PHP into Edge Animate

For a school assignment, I am currently working on a project using edge animate. My objective is to import data from a database hosted on my school's webspace and incorporate it into the edge animate project. Despite researching online for a solution ...

AngularJS flexible route parameter

My AngularJS application has routes that can be either: www.website.com/blog/xyz www.website.com/blog/xyz/title/other-params In the second URL, the title parameter is used for readability purposes only and is not mandatory in the URL. Therefore, I have i ...

Data is not being stored in the MongoDB Model/Schema as expected

I'm encountering an issue with my MongoDB database. It appears to not be receiving the data I am attempting to send to it, resulting in an empty database despite everything else functioning smoothly. The application I'm working on involves scrap ...

Error with the setInterval() method, function is not executing

UPDATED CODE SNIPPET: <script> $.ajaxSetup({ cache : false }); function fetchMessage() { $.get("php/getMessage.php?q=1" + "&" + Date.now(), function(data) { $("#typed").typed({ ...

Executing Node.js child processes: streaming stdout to console as it happens and running the processes one after the other

Details node: v9.4.0 I am looking for a solution to execute external commands sequentially while monitoring the stdout in real-time. The code snippet below demonstrates my attempt to retrieve all test cases from ./test/ and then running them one after ...

Is there a way to modify my function expression without using any state variables?

Currently working on a jQuery game where the player is generated upon clicking a button. Below is the function expression I'm using to store the player's information: var getPlayerData = function() { return { name: $("#name").val(),/ ...

Guide to setting up a horizontal button menu and dropdown submenu beneath the navigation bar using Bootstrap 4

How can I design a horizontal button menu with submenus below the navigation bar in Bootstrap 4? Take a look at the image below to see what I'm aiming for: https://i.sstatic.net/j6b8a.png https://i.sstatic.net/rmtrM.png If you have any ideas or su ...

Disappearing Into the Background Excluding Specific Divs

I have a dilemma with fading in and out a background image using jQuery fadeIn and fadeOut. The issue arises because my wrapper div contains elements such as sidebar and navigation that are positioned absolutely within the wrapper div, causing them to also ...

Troubleshooting Problems with Owl Carousel Loading

Having trouble with Owl Carousel loading issue. I've set up my carousel using the Owl Carousel jQuery plugin as guided, but it's showing me an "owl-carousel loading" class added to the DOM (owl-loading). I've tried adding custom styles and J ...

Attaching to directive parameters

I've been working on creating a draggable div with the ability to bind its location for further use. I'm aiming to have multiple draggable elements on the page. Currently, I've implemented a 'dragable' attribute directive that allo ...

Is there a built-in method in Angular to iterate over an object and update its values?

I have an object with various numbers stored in the object.Value. I want to iterate through them and convert each object.Value to a number with 2 decimal places. What is the correct Angular approach to achieve this? Here is my array: $scope.calendar = [{ ...

It appears that using "object[prop]" as a name attribute does not function properly in HTML

After using console.log on the req.body I received this output: [Object: null prototype] { 'shoe[name]': 'Shoe Name', 'shoe[description]': '', 'shoe[pictures]': '', 'shoe[collections] ...

Issues with cross-site scripting in testacular E2E tests and Angular developments

I am currently in the process of developing a web application using Java on the server side and Angular for the front end. I am facing challenges while setting up end-to-end tests with testacular. The tests are failing due to what seems to be cross-site sc ...

Angular JS has the capability to toggle the visibility of elements on a per-item basis as well as

I have created a repeater that displays a headline and description for each item. I implemented a checkbox to hide all descriptions at once, which worked perfectly. However, I also wanted to allow users to hide or show each description individually. I almo ...

Is there a way to duplicate a GLTF model that has been imported into the Autodesk Viewer?

I encountered an issue while trying to dynamically clone a loaded GLB model and allow the user to position it in the scene. Despite using the model.clone() method, the cloned model ends up appearing at the same position as the original, causing changes in ...