优雅地检查给定日期是否是昨天
假设您有一个Unix时间戳,那么检查该时间戳是否是昨天某个时间的简单和/或优雅方法是什么?
我主要是在寻找Javascript,PHP或C#的解决方案,但也欢迎伪代码和语言无关的解决方案(如果有的话)。
PHP:
$isYesterday = date('Ymd', $timestamp) == date('Ymd', strtotime('yesterday'));
在C#中你可以使用这个:
bool isYesterday = DateTime.Today - time.Date == TimeSpan.FromDays(1);
在伪代码中,要比较时间戳:
- 获取当前的Unix时间戳
- 将检索到的时间戳转换为日期
- 从该日期减去1天
- 将时间戳转换为测试日期
- 比较两个日期。 如果它们相等,则测试时间戳是昨天。
如果向用户显示结果,请注意时区。 对我而言,现在是2010年7月9日13:39。我的14小时前的时间戳是昨天。 但对于不同时区的人来说,现在是15:39,14小时前不是昨天!
另一个问题可能是时间/日期设置错误的系统。 例如,如果您使用JavaScript并且访问者PC的系统时间错误,则程序可能会得出错误的结论。 如果获得正确答案至关重要,请使用正确的时间从已知来源检索当前时间。
你可以在C#中使用它:
bool isYesterday = (dateToCheck.Date.AddDays(1) == DateTime.Now.Date);
Smalltalk中使用Pharo / Squeak的一个例子
(Date year: 2014 month: 4 day: 24) = Date yesterday
这接受可选的DateTimeZone
对象。 如果未给出,则使用当前设置的默认时区。
setTimestamp($timestamp); $t->setTime(0,0); $yesterday = new DateTime("now", $timezone); $yesterday->setTime(0,0); $yesterday = $yesterday->sub(new DateInterval('P1D')); return $t == $yesterday; }
另一个C#示例:
bool isYesterday = DateTime.Now.Date.AddDays(-1) == dateToCheck.Date;
码:
static class ExtensionMethods { private static readonly DateTime UnixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0);; public static bool IsYesterday(this int unixTime) { DateTime convertedTime = UnixStart.AddSeconds(unixTime); return convertedTime.Date == DateTime.Now.AddDays(-1).Date; } public static bool IsYesterday(this DateTime date) { return date.Date == DateTime.Now.AddDays(-1).Date; } }
例子:
public class Examples { public void Tests() { if (1278677571.IsYesterday()) System.Console.WriteLine("Is yesterday"); DateTime aDate = new DateTime(2010, 12, 31); if (aDate.IsYesterday()) System.Console.WriteLine("Is yesterday"); } }
在JavaScript中,你可以写
var someDate = new Date(2010, 6, 9); Date.yesterday.date == someDate.date // true
遗漏了不必要的实施细节,但这是可能的。 好的, 有你去 🙂
(function() { function date(d) { var year = d.getFullYear(); var month = d.getMonth(); var day = d.getDate(); return new Date(year, month, day); } Object.defineProperty(Date, 'yesterday', { enumerable: true, configurable: false, get: function() { var today = new Date(); var millisecondsInADay = 86400000; var yesterday = new Date(today - millisecondsInADay); return yesterday; }, set: undefined }); Object.defineProperty(Date.prototype, 'date', { enumerable: true, configurable: true, get: function() { return date(this).valueOf(); }, set: undefined }); })();
C#
TimeSpan difference = DateTime.Now.Date - olderDate.Date; bool isYesterday = difference.TotalDays == 1;
你可以给这个function一个镜头:
public bool IsFromYesterday(long unixTime) { DateTime convertedTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); convertedTime.AddSeconds(unixTime); DateTime rightNow = DateTime.Now; DateTime startOfToday = DateTime.Today; DateTime startOfYesterday = startOfToday - new TimeSpan(1, 0, 0, 0); if (convertedTime > startOfYesterday && convertedTime < rightNow) return true; else return false; }