Days/Weeks ago from specific date with Moment.js
Asked Answered
N

3

10

I work with moment.js and I have 3 different dates, e.g.

  • 30.07.2018
  • 12.06.2018
  • 10.05.2018

I now try to get the difference in days from these dates until today (if it is less then 7 days ago) or the weeks until today (if it more than 7 days ago) and place it in several spans.

UPDATE thanks Thomas!

I got:

$(document).ready(function(){
    $('.timestamp').html((index, html) => {

        let date = moment(html, "DD.MM.YYYY HH:mm", true), 
        now = moment(),
        days = Math.floor(Math.abs(date - now) / 86400000), 
        weeks = Math.floor(days/7),
        result = date.format("DD.MM.YYYY") + " - ";

      if(weeks){
        result += weeks + (weeks===1? " week ": " weeks ");
        days = days % 7;        
      }

      if(days || weeks===0){
        result += days + (days === 1? " day": " days");
      }

      return result;
    });

});

What I still need:

  • Not showing the initial date, just showing "3 Days". If it delete "result", I want work anymore.

  • Not showing "7 weeks 2 days", this should just be "7 weeks"

Here is the actual fiddle.

Nash answered 1/8, 2018 at 21:39 Comment(3)
jsfiddle.net/r289hvpLTaritariff
@Taritariff thank you so much! Just 2 little things. I don't want to have the output of "DD.MM.YYYY -" only "3 days" is perfect. Second "7 Weeks 2 days" should just be "7 Weeks". Could you help me again?Nash
jsfiddle.net/r289hvpL/21Mirandamire
F
17

You can do this with momentjs diff() method, which can return the difference between two dates in days, weeks, months, hours, minutes, ... based on the option you pass to it.

This is how should be your code:

now = moment()
days = now.diff(date, "days")
weeks = now.diff(date, "weeks")

Demo:

$(document).ready(function() {
  $('.timestamp').html((index, html) => {

    let date = moment(html, "DD.MM.YYYY HH:mm", true),
      now = moment(),
      days = now.diff(date, "days"),
      weeks = now.diff(date, "weeks"),
      result = "";

    if (weeks) {
      result += weeks + (weeks === 1 ? " week " : " weeks ");
      days = days % 7;
    } else if (days || weeks === 0) {
      result += days + (days === 1 ? " day" : " days");
    }

    result += '<br />';
    return result;
  });
});
<span class="timestamp">30.07.2018 00:00</span>
<span class="timestamp">12.06.2018 00:00</span>
<span class="timestamp">10.05.2018 00:00</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
Footpoundsecond answered 2/8, 2018 at 9:7 Comment(4)
Oh nice! And how can I remove the "30.07.2018 - " in front of the "3 days"? If I delete the line "result = date.format("DD.MM.YYYY") + " - ";" it won't work anymore :(Nash
@MaxDiCampo This way you are removing the declaration of result, this will cause errors, you just need to replace result = date.format("DD.MM.YYYY") + " - " with result = "". :)Reinhart
Perfect! Now I am getting crazy and tried to add hours. So if it is "<= 48 hours", show hours, if ">48 hours" show days... I tried.. but I failed... jsfiddle.net/r289hvpL/35 :SNash
You were using a wrong condition, this is an updated fiddle.Reinhart
A
21

Moment.js has fromNow() function that returns "x days" or "x hours ago" from current date/time.

moment([2007, 0, 29]).fromNow();     // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years
Amrita answered 1/7, 2019 at 8:29 Comment(1)
Any idea how you would get that to output how many days or hours ago that date was rather than the number of years as shown in the example?Expressivity
F
17

You can do this with momentjs diff() method, which can return the difference between two dates in days, weeks, months, hours, minutes, ... based on the option you pass to it.

This is how should be your code:

now = moment()
days = now.diff(date, "days")
weeks = now.diff(date, "weeks")

Demo:

$(document).ready(function() {
  $('.timestamp').html((index, html) => {

    let date = moment(html, "DD.MM.YYYY HH:mm", true),
      now = moment(),
      days = now.diff(date, "days"),
      weeks = now.diff(date, "weeks"),
      result = "";

    if (weeks) {
      result += weeks + (weeks === 1 ? " week " : " weeks ");
      days = days % 7;
    } else if (days || weeks === 0) {
      result += days + (days === 1 ? " day" : " days");
    }

    result += '<br />';
    return result;
  });
});
<span class="timestamp">30.07.2018 00:00</span>
<span class="timestamp">12.06.2018 00:00</span>
<span class="timestamp">10.05.2018 00:00</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
Footpoundsecond answered 2/8, 2018 at 9:7 Comment(4)
Oh nice! And how can I remove the "30.07.2018 - " in front of the "3 days"? If I delete the line "result = date.format("DD.MM.YYYY") + " - ";" it won't work anymore :(Nash
@MaxDiCampo This way you are removing the declaration of result, this will cause errors, you just need to replace result = date.format("DD.MM.YYYY") + " - " with result = "". :)Reinhart
Perfect! Now I am getting crazy and tried to add hours. So if it is "<= 48 hours", show hours, if ">48 hours" show days... I tried.. but I failed... jsfiddle.net/r289hvpL/35 :SNash
You were using a wrong condition, this is an updated fiddle.Reinhart
H
1
  const getTime = (date) => {
    let result = moment(date).fromNow();
    const now = moment();
    const days = now.diff(date, 'days');
    const weeks = now.diff(date, 'weeks');
    if (days >= 7) {
      if (days <= 13) {
        result = `a week ago`;
      } else if (days > 13 && days <= 25) {
        result = `${weeks} weeks ago`;
      }
    }
    return result;
  };

  getTime("2023-03-07 12:21:51") // 3 days ago
  getTime("2023-02-28 12:21:51") // a week ago
  getTime("2023-02-07 12:21:51") // a month ago

Hadji answered 10/3, 2023 at 10:58 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Exhortation

© 2022 - 2024 — McMap. All rights reserved.