Why Does Date.Yesterday Counts as Date.Today Also

Why does Date.yesterday counts as Date.today also?

This is happening because calculations.rb is calling the "current" method of the Date class for the configured timezone (Defaults to UTC).

If you open the rails console you can see the date at which "Date.yesterday" is calculating on by doing:

Time.zone.today

This will probably show you tomorrow's date. So Date.yesterday for what rails sees as today, is today. ;)

You can work with the Date library more directly by doing:

Date.today.advance(:days => -1)

This will give you yesterday's date like you expect whereas active_support is returning:

Date.current.advance(:days => -1) 

Why does Date.yesterday() return the day before yesterday in rails?

tl;dr: Use Date.current and Time.current instead of Date.today and Time.now.

Your application has its own time zone, Time.zone. Ruby is not aware of time zones, but Rails is. Rails partially updates Time and Date to be aware of time zones, but not completely. Any methods Rails adds will be time zone aware. Date.yesterday and Date.tomorrow, for example. Built-in Ruby methods it leaves alone, like Date.today. This causes some confusion.

Date.today is giving today according to your local time zone, +0530. Date.yesterday is giving yesterday according to your application's time zone which I'm guessing is +0000 (UTC). 2020-07-10 03:54:46 +0530 is 2020-07-09 22:24:46 UTC so Date.yesterday is 2020-07-08.

Use Date.current instead of Date.today. Date.yesterday is a thin wrapper around Date.current.yesterday. Similarly, use Time.current instead of Time.now.

The ThoughtBot article It's About Time (Zones) discusses Rails time zones in detail and has simple DOs and DON'Ts to avoid time zone confusion.

DON'T USE

  • Time.now
  • Date.today
  • Date.today.to_time
  • Time.parse("2015-07-04 17:05:37")
  • Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z")

DO USE

  • Time.current
  • 2.hours.ago
  • Time.zone.today
  • Date.current
  • 1.day.from_now
  • Time.zone.parse("2015-07-04 17:05:37")
  • Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z").in_time_zone

DateTime.yesterday returns today's date instead of yesterday

It looks like you need to set your timezone. try this:

> z = "Pacific Time (US & Canada)" 
=> "Pacific Time (US & Canada)"
> 0.days.ago.in_time_zone(z)
=> Mon, 02 Jan 2012 18:37:50 PST -08:00

Then add something like this to application.rb:

 config.time_zone = "Pacific Time (US & Canada)" 

If date is todays date display today, or yesterday

There might be a built-in solution with Shopify, but if not, running this script after page load should give you a way to do what you want.

Note though, that the date to calc. need to have the year as well, or else it will go wrong.


Update after request to not show the year

To show the date without year, you could do like this instead, where you can format the visible date any way you like, as it uses the data-date value for calc.

A positive side effect with this is, that if you need the date it will still be there in the data-date attribute.

<span class="date" data-date='{{ article.published_at | date: "%F" }}'>{{ article.created_at | date: "%A, %-d. %B" }}</span>

Updated sample

function makeYMD(d) {  return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();}function getYesterday(d) {  return new Date(d.setDate(d.getDate() - 1));}
var span = document.querySelector('span.date');var spandate = new Date(span.getAttribute("data-date"));var today = new Date();var yesterday = getYesterday(new Date());
spandate = makeYMD(spandate);today = makeYMD(today);yesterday = makeYMD(yesterday);

if(today == spandate) { span.textContent = "Today";} else if(yesterday == spandate) { span.textContent = "Yesterday";}
<span class="date" data-date='2016-01-31'>Monday, 31. January</span>

PHP: date Yesterday, Today

function get_day_name($timestamp) {

$date = date('d/m/Y', $timestamp);

if($date == date('d/m/Y')) {
$date = 'Today';
}
else if($date == date('d/m/Y',now() - (24 * 60 * 60))) {
$date = 'Yesterday';
}
return $date;
}
print date('G:i:s', $last_access).' '.get_day_name($last_access);

Javascript code for showing yesterday's date and todays date

Yesterday's date is simply today's date less one, so:

var d = new Date();
d.setDate(d.getDate() - 1);

If today is 1 April, then it is set to 0 April which is converted to 31 March.

Since you also wanted to do some other stuff, here are some functions to do it:

// Check if d is a valid date
// Must be format year-month name-date
// e.g. 2011-MAR-12 or 2011-March-6
// Capitalisation is not important
function validDate(d) {
var bits = d.split('-');
var t = stringToDate(d);
return t.getFullYear() == bits[0] &&
t.getDate() == bits[2];
}

// Convert string in format above to a date object
function stringToDate(s) {
var bits = s.split('-');
var monthNum = monthNameToNumber(bits[1]);
return new Date(bits[0], monthNum, bits[2]);
}

// Convert month names like mar or march to
// number, capitalisation not important
// Month number is calendar month - 1.
var monthNameToNumber = (function() {
var monthNames = (
'jan feb mar apr may jun jul aug sep oct nov dec ' +
'january february march april may june july august ' +
'september october november december'
).split(' ');

return function(month) {
var i = monthNames.length;
month = month.toLowerCase();

while (i--) {
if (monthNames[i] == month) {
return i % 12;
}
}
}
}());

// Given a date in above format, return
// previous day as a date object
function getYesterday(d) {
d = stringToDate(d);
d.setDate(d.getDate() - 1)
return d;
}

// Given a date object, format
// per format above
var formatDate = (function() {
var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
function addZ(n) {
return n<10? '0'+n : ''+n;
}
return function(d) {
return d.getFullYear() + '-' +
months[d.getMonth()] + '-' +
addZ(d.getDate());
}
}());

function doStuff(d) {

// Is it format year-month-date?
if (!validDate(d)) {
alert(d + ' is not a valid date');
return;
} else {
alert(d + ' is a valid date');
}
alert(
'Date in was: ' + d +
'\nDay before: ' + formatDate(getYesterday(d))
);
}

doStuff('2011-feb-08');
// Shows 2011-feb-08 is a valid date
// Date in was: 2011-feb-08
// Day before: 2011-feb-07

Formatting yesterday's date in python

Use datetime.timedelta()

>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'


Related Topics



Leave a reply



Submit