9

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.

Community
  • 1
  • 1
Forivin
  • 14,780
  • 27
  • 106
  • 199

8 Answers8

12

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
Kapilrc
  • 1,362
  • 15
  • 11
  • 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. – Pape May 11 '21 at 11:05
  • 1
    @Pape, nice analysis. The code is fixed now. Thank you! – Kapilrc May 16 '21 at 12:54
  • 2
    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. – BrunoElo Sep 09 '21 at 17:07
6

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";
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • 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 Aug 25 '15 at 09:30
4

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
Pape
  • 109
  • 7
1
  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
    }
    
Ivan1987
  • 11
  • 1
1

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();
  }
adrisons
  • 3,443
  • 3
  • 32
  • 48
1

This works for me.

const generatingDates = () => {
  let dates = {
    today: null,
    yesterday: null,
    oneDayBeforeYesterday: null,
    twoDayBeforeYesterday: null,
    threeDayBeforeYesterday: null,
    fourDayBeforeYesterday: null,
    fiveDayBeforeYesterday: null,
  };
 
  let keys = Object.keys(dates);
 
  keys.map((x) => {
    prev = null;
    if (prev === null && dates[x] === null) {
      dates[x] = new Date();
      prev = dates[x];
    } else if (value === null && prev !== null) {
      dates[x] = prev;
    }
  });
 
  return dates;
};
 
function findDay(date) {
  let dateToCheck = new Date(date);
 
  const datesDict = generatingDates();
  //   console.log(datesDict);
 
  datesDict.yesterday.setDate(datesDict.yesterday.getDate() - 1);
  datesDict.oneDayBeforeYesterday.setDate(datesDict.yesterday.getDate() - 1);
  datesDict.twoDayBeforeYesterday.setDate(datesDict.yesterday.getDate() - 2);
  datesDict.threeDayBeforeYesterday.setDate(datesDict.yesterday.getDate() - 3);
  datesDict.fourDayBeforeYesterday.setDate(datesDict.yesterday.getDate() - 4);
  datesDict.fiveDayBeforeYesterday.setDate(datesDict.yesterday.getDate() - 5);
 
  let days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
 
  if (dateToCheck.toDateString() === datesDict.today.toDateString()) {
    return "Today";
  } else if (
    dateToCheck.toDateString() === datesDict.yesterday.toDateString()
  ) {
    return "Yesterday";
  } else if (
    dateToCheck.toDateString() ===
    datesDict.oneDayBeforeYesterday.toDateString()
  ) {
    return days[date.getDay()];
  } else if (
    dateToCheck.toDateString() ===
    datesDict.twoDayBeforeYesterday.toDateString()
  ) {
    return days[date.getDay()];
  } else if (
    dateToCheck.toDateString() ===
    datesDict.threeDayBeforeYesterday.toDateString()
  ) {
    return days[date.getDay()];
  } else if (
    dateToCheck.toDateString() ===
    datesDict.fourDayBeforeYesterday.toDateString()
  ) {
    return days[date.getDay()];
  } else if (
    dateToCheck.toDateString() ===
    datesDict.fiveDayBeforeYesterday.toDateString()
  ) {
    return days[dateToCheck.getDay()];
  } else {
    return dateToCheck;
  }
}
Nabeel Ahmed
  • 31
  • 1
  • 4
0

You can use this function and pass your date as a parameter and it will return day of week and after 7 days it will return given date.

function findDay(date) {
    let dateToCheck = new Date(date);
    
    const today = new Date();
    const yesterday = new Date(today);
    const oneDayBeforeYesterday = new Date(yesterday);
    const twoDayBeforeYesterday = new Date(yesterday);
    const threeDayBeforeYesterday = new Date(yesterday);
    const fourDayBeforeYesterday = new Date(yesterday);
    const fiveDayBeforeYesterday = new Date(yesterday);

    yesterday.setDate(yesterday.getDate() - 1);
    oneDayBeforeYesterday.setDate(yesterday.getDate() - 1);
    twoDayBeforeYesterday.setDate(yesterday.getDate() - 2);
    threeDayBeforeYesterday.setDate(yesterday.getDate() - 3);
    fourDayBeforeYesterday.setDate(yesterday.getDate() - 4);
    fiveDayBeforeYesterday.setDate(yesterday.getDate() - 5);

    let days = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
    ];

    if (dateToCheck.toDateString() === today.toDateString()) {
        return "Today";
    } else if (dateToCheck.toDateString() === yesterday.toDateString()) {
        return "Yesterday";
    } else if (dateToCheck.toDateString() === oneDayBeforeYesterday.toDateString()) {
        return days[date.getDay()];
    } else if (dateToCheck.toDateString() === twoDayBeforeYesterday.toDateString()) {
        return days[date.getDay()];
    } else if (dateToCheck.toDateString() === threeDayBeforeYesterday.toDateString()) {
        return days[date.getDay()];
    } else if (dateToCheck.toDateString() === fourDayBeforeYesterday.toDateString()) {
        return days[date.getDay()];
    } else if (dateToCheck.toDateString() === fiveDayBeforeYesterday.toDateString()) {
        return days[dateToCheck.getDay()];
    } else {
        return dateToCheck;
    }
}

console.log(findDay("07-10-2020"));
m3nda
  • 1,986
  • 3
  • 32
  • 45
  • 1
    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. – m3nda May 18 '21 at 04:01
-1

You can use the date difference between two dates it will return difference in days if there is minus value then like

var date1 = new Date("12/15/2010");
var date2 = new Date("12/14/2010");
var timeDiff = date2.getTime() - date1.getTime();
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
if(diffDays == -1){ alert("Yesterday")}
Muhammad Usman
  • 1,366
  • 5
  • 18
  • 33
  • 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 Aug 25 '15 at 09:50
  • No, you have to compare the current time with on of those. Check this: http://jsfiddle.net/1psf0ysb/ – Forivin Aug 25 '15 at 10:06
  • @Forivin I got it that is Time issue (means time in pm and am etc) you can check it here now http://jsfiddle.net/1psf0ysb/1/ – Muhammad Usman Aug 25 '15 at 10:14
  • Well, that's not getting me anywhere, you just removed the time. My dates have times and I need them... – Forivin Aug 25 '15 at 10:23
  • 4
    Bad, as it won't detect yesterday if it less than 24 hours ago: http://jsfiddle.net/JS69L/1720/ – Jorge Fuentes González Sep 11 '17 at 01:01