Check if date is today, was yesterday or was in the last 7 days

18,972

Solution 1

If you want to print today, yesterday, display the day of the week, display date without year if current year and display date with the year if the previous year, below code will help you.

var fulldays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];


function formatDate(someDateTimeStamp) {
    var dt = new Date(someDateTimeStamp),
        date = dt.getDate(),
        month = months[dt.getMonth()],
        timeDiff = someDateTimeStamp - Date.now(),
        diffDays = new Date().getDate() - date,
        diffMonths = new Date().getMonth() - dt.getMonth(),
        diffYears = new Date().getFullYear() - dt.getFullYear();

    if(diffYears === 0 && diffDays === 0 && diffMonths === 0){
      return "Today";
    }else if(diffYears === 0 && diffDays === 1) {
      return "Yesterday";
    }else if(diffYears === 0 && diffDays === -1) {
      return "Tomorrow";
    }else if(diffYears === 0 && (diffDays < -1 && diffDays > -7)) {
      return fulldays[dt.getDay()];
    }else if(diffYears >= 1){
      return month + " " + date + ", " + new Date(someDateTimeStamp).getFullYear();
      }else {
        return month + " " + date;
      }
}

formatDate(Date.now()) //"Today"
formatDate(Date.now() - 86400000) // "Yesterday"
formatDate(Date.now() - 172800000) // it will return the name of the week if it is beyond two days

Solution 2

Okay, we can do it in these steps:

  1. Get the two dates' Date() objects.
  2. Set the time using .setTime() to a particular time for both.
  3. Using .getTime(), calculate the milliseconds.
  4. Make the calculation of time for both the dates.
  5. Check the following cases:
    1. If the difference is 86400000, it is yesterday.
    2. If the difference is a multiple of 86400000, it is the number of days.

JavaScript Code

var a = new Date(2015, 8 - 1, 25);  // Today
var b = new Date(2015, 8 - 1, 24);  // Yesterday
var c = new Date();                 // Now

c.setHours(0);
c.setMinutes(0);
c.setSeconds(0, 0);

if (a.getTime() == c.getTime())
  return "Today";
else if (b.getTime() == c.getTime())
  return "Yesterday";
else if ((new Date(2015, 8 - 1, 25 - 7)).getTime() < c.getTime())
  return "Less than a week";

Solution 3

I've built upon @Kapilrc source code. The language variable should be valid for toLocaleString(). Enjoy!

function create_human_friendly_date(
  timestamp,
  yesterday_text,
  today_text,
  tomorrow_text,
  language
) {
  var in_the_last_7days_date_options = { weekday: 'long'};
  var in_the_next_7days_date_options = { month: 'short', day: 'numeric' };
  var same_year_date_options = { month: 'short', day: 'numeric' };
  var far_date_options = { year: 'numeric', month: 'short', day: 'numeric' };

  var dt = new Date(timestamp);
  var date = dt.getDate();
  var time_diff = timestamp - Date.now();
  var diff_days = new Date().getDate() - date;
  var diff_months = new Date().getMonth() - dt.getMonth();
  var diff_years = new Date().getFullYear() - dt.getFullYear();

  var is_today = diff_years === 0 && diff_months === 0 && diff_days === 0;
  var is_yesterday = diff_years === 0 && diff_months === 0 && diff_days === 1;
  var is_tomorrow = diff_years === 0 && diff_months === 0 && diff_days === -1;
  var is_in_the_last_7days = diff_years === 0 && diff_months === 0 && (diff_days > 1 && diff_days < 7);
  var is_in_the_next_7days = diff_years === 0 && diff_months === 0 && (diff_days < -1 && diff_days > -7);
  var is_same_year = diff_years === 0;

  if(is_today){
    return today_text;
  }else if(is_yesterday) {
    return yesterday_text;
  }else if(is_tomorrow) {
    return tomorrow_text;
  }else if(is_in_the_last_7days) {
    return dt.toLocaleString(language, in_the_last_7days_date_options);
  }else if(is_in_the_next_7days) {
    return dt.toLocaleString(language, in_the_next_7days_date_options);
  }else if(is_same_year){
    return dt.toLocaleString(language, same_year_date_options);
  }else{
    return dt.toLocaleString(language, far_date_options);
  }
}

console.log(create_human_friendly_date(Date.now(), "Yesterday", "Today", "Tomorrow", "en")); // Today

console.log("***********************************");

console.log(create_human_friendly_date(Date.now() - (1000 * 3600 * 24 * 1), "Yesterday", "Today", "Tomorrow", "en")); // Yesterday
console.log(create_human_friendly_date(Date.now() - (1000 * 3600 * 24 * 2), "Yesterday", "Today", "Tomorrow", "en")); // 2 days ago
console.log(create_human_friendly_date(Date.now() - (1000 * 3600 * 24 * 10), "Yesterday", "Today", "Tomorrow", "en")); // 10 days ago
console.log(create_human_friendly_date(Date.now() - (1000 * 3600 * 24 * 900), "Yesterday", "Today", "Tomorrow", "en")); // Some years ago

console.log("***********************************");

console.log(create_human_friendly_date(Date.now() + (1000 * 3600 * 24 * 1), "Yesterday", "Today", "Tomorrow", "en")); // Tomorrow
console.log(create_human_friendly_date(Date.now() + (1000 * 3600 * 24 * 2), "Yesterday", "Today", "Tomorrow", "en")); // In 2 days
console.log(create_human_friendly_date(Date.now() + (1000 * 3600 * 24 * 10), "Yesterday", "Today", "Tomorrow", "en")); // In 10 days
console.log(create_human_friendly_date(Date.now() + (1000 * 3600 * 24 * 900), "Yesterday", "Today", "Tomorrow", "en")); // In some years

Solution 4

This works for me:

  private _isSameDay(date1: Date, date2: Date): boolean {
    return (
      date1.getUTCFullYear() === date2.getUTCFullYear() &&
      date1.getMonth() === date2.getMonth() &&
      date1.getDate() === date2.getDate()
    );
  }

  private _getSeparatorBody(date: Date): string {
    if (this._isSameDay(date, new Date())) {
      return 'Today';
    }
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    if (this._isSameDay(date, yesterday)) {
      return 'Yesterday';
    }
    return date.toISOString();
  }

Solution 5

  1. Why don't you try something like this
  2. You can do this also for 7 days ago:

    export function isToday(date, now) {
      const yearDate = date.getYear();
      const monthDate = date.getMonth();
      const dayDate = date.getDate();
      const yearNow = now.getYear();
      const monthNow = now.getMonth();
      const dayNow = now.getDate();
      if (yearDate === yearNow && monthDate === monthNow && dayDate === 
        dayNow) {
        return true
      }
      return false
    }
    
Share:
18,972
Forivin
Author by

Forivin

Open source, security, Linux, DIY electronics enthusiast and privacy advocate.

Updated on June 09, 2022

Comments

  • Forivin
    Forivin almost 2 years

    I know of this thread: Elegantly check if a given date is yesterday
    But I'm just specifically looking for a JavaScript solution. If possible a short one. I couldn't really figure out a 100% reliable way..

    This is how I have done it so far:

    function FormatDate(someDtUTC) {
        var someDt = new Date(someDtUTC.getTime() + someDtUTC.getTimezoneOffset() * 60 * 1000);
        var dtNow = new Date();
        if (dtNow.getUTCFullYear() == someDt.getUTCFullYear() && dtNow.getUTCMonth() == someDt.getUTCMonth()) {
            if (dtNow.getUTCDate() == someDt.getUTCDate())
                var dateString = "Today, " + Ext.Date.format(someDt, 'G:i'); // Today, 15:32
            else if (dtNow.getUTCDate() - 1 == someDt.getUTCDate())
                var dateString = "Yesterday, " + Ext.Date.format(someDt, 'G:i'); //Yesterday, 13:26
            else if (dtNow.getUTCDate() - someDt.getUTCDate() < 7)
                var dateString = Ext.Date.format(someDt, 'l, G:i'); //Sunday, 14:03
        } else
            var dateString = Ext.Date.format(someDt, 'j.n.y\, G:i'); //7.8.15, 8:25
        return dateString;
    }
    

    Don't worry about the Ext.Date.format() function, it's not part of the question.

    The problem with that code is, that it can't handle situations like:

    Today: 01.08.15  
    Yesterday: 31.07.15 
    

    Any idea how I could tell the function to handle that as well?
    I'm not looking for a solution with exterenal libraries (that includes ExtJS). I'd like to solve this with raw JavaScript.

  • Forivin
    Forivin over 8 years
    By setting the time I would manipulate the date object, right? I'd really like to be able to get the original time from the objects afterwards.
  • Forivin
    Forivin over 8 years
    This returned -1 for both of these: Sun Aug 23 2015 12:39:34 GMT+0200 (Central Europe Daylight Time) Mon Aug 24 2015 10:30:17 GMT+0200 (Central Europe Daylight Time)
  • Forivin
    Forivin over 8 years
    No, you have to compare the current time with on of those. Check this: jsfiddle.net/1psf0ysb
  • Muhammad Usman
    Muhammad Usman over 8 years
    @Forivin I got it that is Time issue (means time in pm and am etc) you can check it here now jsfiddle.net/1psf0ysb/1
  • Forivin
    Forivin over 8 years
    Well, that's not getting me anywhere, you just removed the time. My dates have times and I need them...
  • Jorge Fuentes González
    Jorge Fuentes González over 6 years
    Bad, as it won't detect yesterday if it less than 24 hours ago: jsfiddle.net/JS69L/1720
  • Pape
    Pape almost 3 years
    That is excellent. But you need to check the month too for the "today" section otherwise today is today and the same day last month will also return today.
  • Kapilrc
    Kapilrc almost 3 years
    @Pape, nice analysis. The code is fixed now. Thank you!
  • m3nda
    m3nda almost 3 years
    I've tried this and works, i've edit myDate to date, but dateToCheck should work. I'm sure this function can be shorted a lot.
  • BrunoElo
    BrunoElo over 2 years
    What about the condition for yesterday...I think diffMonths should be checked else yesterday is yesterday and the same day some other month in same year will also return yesterday.