Comparing two date and check if given date is in past or same or future - momentjs

I am using moment.js to compare two dates.
const somedayMom = moment(new Date(event.target.value)); // '2021-12-31'
const todayMom = moment();
if (moment(somedayMom).isSameOrAfter(todayMom)) {
} else {
}
Now from input I am getting '2021-12-31' and today is 31st December, so it should fall in if() block, but it falls into else part. What I am doing wrong here. please help

Use .format to include only year, month and day.
if (moment(somedayMom.format('YYYY-MM-DD')).isSameOrAfter(todayMom.format('YYYY-MM-DD'))) {
}
else {
}
PS. Formatting the first moment would be unneccessary in your scenaro if event.target.value returns a right string.

Related

SwiftUI or Combine Clock/Timer events

Using SwiftUI (or Combine) how might I set up a series of one or more events that are triggered by the (system) clock. Examples might include:
Every night at midnight,
On the hour,
Every fifteen minutes on the quarter hour,
Finally, on a slightly different note: On the 29th of February 2020 at 12:15.
An approximation is easily achieved by setting up a timer event that fires every second and then checking the hours/minutes/seconds, etc. but this seems very inefficient for events that may be many hours or days apart.
I'm looking for something that is closely synchronised to the actual system clock and fires off a single event at the required time rather than firing loads of events and having each one ask "Are we there yet?".
I would suggest the following:
DispatchQueue.global(qos: .background).async {
let isoDate = "2020-01-13T16:58:30+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
let t = Timer(fire: date, interval: 2, repeats: true) { timer in
print("fired")
}
let runLoop = RunLoop.current
runLoop.add(t, forMode: .default)
runLoop.run()
}
string to date conversion I used this answer to format the time correctly.
The example is in GMT.
documentation apple you can look up timer tolerance which can be adjusted if you need the timer to be very accurate.
interval is in seconds so this solution won't get more accurate than seconds
You might want to enable the Background Modes capability to go for the very long running timers. Never done that so I can't help here.
All your examples should work. I hope this helps!
I had to implement this feature too using Combine / SwiftUI : a Timer that would execute at start then every day, hour or minutes (for testing), here is my solution if it can be useful or improved :)
class PeriodicPublisher {
var periodicFormat: PeriodicFormat = .daily
init(_ format: PeriodicFormat = .daily) {
self.periodicFormat = format
}
// Must have an equatable for removeDuplicate
struct OutputDate: Equatable {
let compared: String
let original: String
init(_ comparedDatePart: String, _ originalDate: String) {
self.compared = comparedDatePart
self.original = originalDate
}
static func ==(lhs: OutputDate, rhs: OutputDate) -> Bool {
return lhs.compared == rhs.compared
}
}
enum PeriodicFormat {
case daily
case hourly
case minutely
func toComparableDate() -> String {
switch self {
case .daily:
return "yyyy-MM-dd"
case .hourly:
return "HH"
case .minutely:
return "mm"
}
}
}
func getPublisher() -> AnyPublisher<OutputDate, Never> {
let compareDateFormatter = DateFormatter()
compareDateFormatter.dateFormat = self.periodicFormat.toComparableDate()
let originalTimerDateFormatter = DateFormatter()
originalTimerDateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
var nowDate: Just<OutputDate> {
let comparedDate = compareDateFormatter.string(from: Date())
let originalDate = originalTimerDateFormatter.string(from: Date())
return Just(OutputDate(comparedDate, originalDate))
}
let timerDate = Timer.publish(every: 2.0, tolerance: 1.0, on: .main, in: .default, options: nil)
.autoconnect()
.map { dateString -> OutputDate in
return OutputDate(compareDateFormatter.string(from: dateString), originalTimerDateFormatter.string(from: dateString))
}
.eraseToAnyPublisher()
return Publishers.Merge(nowDate, timerDate)
.map { $0 }
.removeDuplicates()
.eraseToAnyPublisher()
}
}
How does it work ?
Every 2 seconds the scheduler issue current date (with Timer.publish()), this date is used to create a "OutputDate" holding two properties : one "comparable" part used to compare if something has changed and one "original" part so it can be useful for the consumer.
Comparable property is Timer's date formatted with toComparableDate given the provided configuration (.daily, .hourly, .minutely). Using "removeDuplicates" on this property allow to publish "OutputDate" only when this value changes. Every day or hour or minute.
Publishers.Merge is used to publish a value immediately after instantiation, otherwise nothing happens before the first Timer.publish(every). Here 2 seconds.
How to use it ?
You would use it with Combine like this :
PeriodicPublisher(.daily).getPublisher().sink { date in
print("Day has changed \(date.original)")
}

Why is the end date for one more day?

select: function(start, end) {
var formatStart = start.format();
var formatEnd = end.format();
alert(formatEnd);
showProjModal(formatStart,formatEnd);
},
i choice 2016-08-11 to 2016-08-13,but formatEnd is 2016-08-14,i do not know why?
From the docs at fullcalendar.io.
end is a Moment indicating the end of the selection. It is an exclusive value, so if the selection is all-day, and the last day is a Thursday, end will be Friday.
I guess your selection is all day? So it is working as intended.
You can check this by calling hasTime
Example
if (end.hasTime()) {
// Specific endpoint. For example 2016-07-13 10:00:00'
}
else {
// All day. For example 2016-07-13
// If you want to output the end day you selected here subtract 1 of the day
end.subtract(1, 'days');
}

How to get ReferenceTime without time

MomentJS has option "referanceTime" - http://momentjs.com/docs/#/displaying/calendar-time/ and it displays datetime like this Last Monday 2:30 AM
Problem is when I have date without time - it displays Last Monday 0:00 AM - how get rid of time when date hasn't got it?
Very similar to my answer here but slightly more advanced.
I believe the only way to customize calendar time is by using a custom locale. In your case, you need to use a custom function.
Here's a somewhat complex, but complete way to do it:
// Factory-type function that returns a function.
// Used to set argument (fstr) without using `bind` (since bind changes `this`)
var stripZeroTime = function (fstr) {
return function () {
if (this.format("H:mm:ss") === "0:00:00") { // if midnight
return fstr.replace("LT", "") //remove time
.replace("at", "") //remove at
.replace(/\s+/g, ' ').trim(); //strip extra spaces
}
return fstr;
}
}
moment.locale('en-cust', {
calendar: {
lastDay: stripZeroTime('[Yesterday at] LT'), // Default format strings
sameDay: stripZeroTime('[Today at] LT'),
nextDay: stripZeroTime('[Tomorrow at] LT'),
lastWeek: stripZeroTime('[last] dddd [at] LT'),
nextWeek: stripZeroTime('dddd [at] LT'),
sameElse: stripZeroTime('L')
}
});
Demo with test cases
A simpler way would be to just strip off the 0:00:00 when it's midnight.
function stripMidnight(m){
if(m.format("H:mm:ss") === "0:00:00"){
return m.calendar().replace("0:00:00","");
}else{
return m.calendar();
}
}
Since 2.10.5 we can define our own render engine by invocation (second parameter of calendar function) - http://momentjs.com/docs/#/displaying/calendar-time/
But now we can use only strings not function to define pattern

Moment JS - check if a date is today or in the future

I am trying to use momentjs to check if a given date is today or in the future.
This is what I have so far:
<script type="text/javascript" src="http://momentjs.com/downloads/moment.min.js"></script>
<script type="text/javascript">
var SpecialToDate = '31/01/2014'; // DD/MM/YYYY
var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment().diff(SpecialTo) > 0) {
alert('date is today or in future');
} else {
alert('date is in the past');
}
</script>
The code is evaluating my date (31st of Jan 2014) as a date in past.
Any idea what I am doing wrong?
You can use the isSame function:
var iscurrentDate = startTime.isSame(new Date(), "day");
if(iscurrentDate) {
}
After reading the documentation: http://momentjs.com/docs/#/displaying/difference/, you have to consider the diff function like a minus operator.
// today < future (31/01/2014)
today.diff(future) // today - future < 0
future.diff(today) // future - today > 0
Therefore, you have to reverse your condition.
If you want to check that all is fine, you can add an extra parameter to the function:
moment().diff(SpecialTo, 'days') // -8 (days)
Since no one seems to have mentioned it yet, the simplest way to check if a Moment date object is in the past:
momentObj.isBefore()
Or in the future:
momentObj.isAfter()
Just leave the args blank -- that'll default to now.
There's also isSameOrAfter and isSameOrBefore.
N.B. this factors in time. If you only care about the day, see Dipendu's answer.
// Returns true if it is today or false if it's not
moment(SpecialToDate).isSame(moment(), 'day');
You can use the isAfter() query function of momentjs:
Check if a moment is after another moment.
moment('2010-10-20').isAfter('2010-10-19'); // true
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
moment('2010-10-20').isAfter('2010-01-01', 'year'); // false
moment('2010-10-20').isAfter('2009-12-31', 'year'); // true
http://momentjs.com/docs/#/query/is-after/
Update
moment().isSame('2010-02-01', 'day'); // Return true if we are the 2010-02-01
I have since found the isSame function, which in I believe is the correct function to use for figuring out if a date is today.
Original answer
Just in case someone else needs this, just do this:
const isToday = moment(0, "HH").diff(date, "days") == 0;
or if you want a function:
isToday = date => moment(0,"HH").diff(date, "days") == 0;
Where date is the date you want to check for.
Explanation
moment(0, "HH") returns today's day at midnight.
date1.diff(date2, "days") returns the number of days between the date1 and date2.
invert isBefore method of moment to check if a date is same as today or in future like this:
!moment(yourDate).isBefore(moment(), "day");
To check if it is today:
If we compare two dates which contain also the time information isSame will obviously fail. diff will fail in case that the two dates span over the new day:
var date1 = moment("01.01.2016 23:59:00", "DD.MM.YYYY HH.mm.ss");
var date2 = moment("02.01.2016 00:01:00", "DD.MM.YYYY HH.mm.ss");
var diff = date2.diff(date1); // 2seconds
I think the best way, even if it is not quick and short, is the following:
var isSame = date1.date() == date2.date() && date1.month() == date2.month() && date1.year() == date2.year()
To check if it is in the future:
As suggested also by other users, the diff method works.
var isFuture = now.diff(anotherDate) < 0
If you only need to know which one is bigger, you can also compare them directly:
var SpecialToDate = '31/01/2014'; // DD/MM/YYYY
var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment() > SpecialTo) {
alert('date is today or in future');
} else {
alert('date is in the past');
}
Hope this helps!
Use the simplest one to check for future date
if(moment().diff(yourDate) >= 0)
alert ("Past or current date");
else
alert("It is a future date");
if firstDate is same or after(future) secondDate return true else return false. Toda is firstDate = new Date();
static isFirstDateSameOrAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
var date1 = moment(firstDate);
var date2 = moment(secondDate);
if(date1 && date2){
return date1.isSameOrBefore(date2,'day');
}
return false;
}
There is isSame, isBefore and isAfter for day compare moment example;
static isFirstDateSameSecondDate(firstDate: Date, secondDate: Date): boolean {
var date1 = moment(firstDate);
var date2 = moment(secondDate);
if (date1 && date2) {
return date1.isSame(date2,'day');
}
return false;
}
static isFirstDateAfterSecondDate(firstDate: Date, secondDate: Date): boolean {
var date1 = moment(firstDate);
var date2 = moment(secondDate);
if(date1 && date2){
return date1.isAfter(date2,'day');
}
return false;
}
static isFirstDateBeforeSecondDate(firstDate: Date, secondDate: Date): boolean {
var date1 = moment(firstDate);
var date2 = moment(secondDate);
if(date1 && date2){
return date1.isBefore(date2,'day');
}
return false;
}
I wrote functions that check if a date of Moment type is a Day that Passed or not, as functional and self-descriptive functions.
Maybe it is could to help someone.
function isItBeforeToday(MomentDate: Moment) {
return MomentDate.diff(moment(0, 'HH')) < 0;
}
function isItAfterToday(MomentDate: Moment) {
return MomentDate.diff(moment(0, 'HH')) > 0;
}
Select yesterday to check past days or not with help of moment().subtract(1, "day");
Reference:- http://momentjs.com/docs/#/manipulating/subtract/
function myFunction() {
var yesterday = moment().subtract(1, "day").format("YYYY-MM-DD");
var SpecialToDate = document.getElementById("theDate").value;
if (moment(SpecialToDate, "YYYY-MM-DD", true).isAfter(yesterday)) {
alert("date is today or in future");
console.log("date is today or in future");
} else {
alert("date is in the past");
console.log("date is in the past");
}
}
<script src="http://momentjs.com/downloads/moment.js"></script>
<input type="date" id="theDate" onchange="myFunction()">
function isTodayOrFuture(date){
date = stripTime(date);
return date.diff(stripTime(moment.now())) >= 0;
}
function stripTime(date){
date = moment(date);
date.hours(0);
date.minutes(0);
date.seconds(0);
date.milliseconds(0);
return date;
}
And then just use it line this :
isTodayOrFuture(YOUR_TEST_DATE_HERE)
If we want difference without the time you can get the date different (only date without time) like below, using moment's format.
As, I was facing issue with the difference while doing ;
moment().diff([YOUR DATE])
So, came up with following;
const dateValidate = moment(moment().format('YYYY-MM-DD')).diff(moment([YOUR SELECTED DATE HERE]).format('YYYY-MM-DD'))
IF dateValidate > 0
//it's past day
else
//it's current or future
Please feel free to comment if there's anything to improve on.
Thanks,
i wanted it for something else but eventually found a trick which you can try
somedate.calendar(compareDate, { sameDay: '[Today]'})=='Today'
var d = moment();
var today = moment();
console.log("Usign today's date, is Date is Today? ",d.calendar(today, {
sameDay: '[Today]'})=='Today');
var someRondomDate = moment("2012/07/13","YYYY/MM/DD");
console.log("Usign Some Random Date, is Today ?",someRondomDate.calendar(today, {
sameDay: '[Today]'})=='Today');
var anotherRandomDate = moment("2012/07/13","YYYY/MM/DD");
console.log("Two Random Date are same date ? ",someRondomDate.calendar(anotherRandomDate, {
sameDay: '[Today]'})=='Today');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
check with following:
let isContinue = moment().diff('2020-04-04T20:06:11+05:30')/1000
it is returning in seconds..
If will check as 2 mins condition then
if (isContinue < 120) {
..To check otp details or further logic
} else {
// otp is getting invalid
}
Simplest answer will be:
const firstDate = moment('2020/10/14'); // the date to be checked
const secondDate = moment('2020/10/15'); // the date to be checked
firstDate.startOf('day').diff(secondDate.startOf('day'), 'days'); // result = -1
secondDate.startOf('day').diff(firstDate.startOf('day'), 'days'); // result = 1
It will check with the midnight value and will return an accurate result. It will work also when time diff between two dates is less than 24 hours also.

How to determine the entire date range displayed by ASP.NET calendar?

The ASP.NET calendar always displays 6 weeks of dates in a 7x6 grid. My problem is that the first day of the target month does not necessarily appear in the first row... in some cases, the entire first row displays dates from the previous month. In other cases, the entire last row displays dates from the next row.
Is there a reliable way to query the calendar object to determine the 42-day range that would be rendered for a specific month/year?
For example, consider June 2008 and Feb 2009:
Notice that the first week contains ONLY dates from prior month http://img371.imageshack.us/img371/2290/datesmq5.png
I assume that the calendar tries to avoid bunching all of the "other month" dates at either the top or bottom of the grid, and therefore puts the first of the target month on the 2nd row. I am looking for an easy way to determine that the displayed range for June 2008 is May 25 - July 5, for instance.
Looking at the public members exposed by the ASP.NET Calendar control I do not believe that this information is something that you can just get from the calendar control.
You have a few options as "workarounds" to this though, although not nice....but they would work.
You could manually calculate the first week values
You can handle the "day render" event to handle the binding of the individual days, and record min/max values.
Granted neither is elegant, but AFAIK it is the only real option
Edit
After discussion in the comments, another option is a modified version of my second option above. Basically the first time Day Render is called, get the block of data for the next 42 days, then you can simply search the list for the proper day value to display on future calls to DayRender, avoiding a DB hit for each day. Doing this is another "non-elegant" solution, but it works, and reduces a bit of load on the DB, but introduces some overhead on the application side.
It will be important here to define well structured page level properties to hold the items during the binding events, but to ensure that if a month changed, etc that it wasn't loaded incorrectly etc.
I wrote a couple of methods to help with this. Just pass in Calendar.VisibleDate:
public static DateTime GetFirstDateOfMonth(DateTime date)
{
return new DateTime(date.Year, date.Month, 1);
}
public static DateTime GetFirstDisplayedDate(DateTime date)
{
date = GetFirstDateOfMonth(date);
return date.DayOfWeek == DayOfWeek.Sunday ? date.AddDays(-7) : date.AddDays((int)date.DayOfWeek * -1);
}
public static List<DateTime> GetDisplayedDates(DateTime date)
{
date = GetFirstDisplayedDate(date);
List<DateTime> dates = new List<DateTime>();
for (int i = 0; i < 42; i++)
{
dates.Add(date.AddDays(i));
}
return dates;
}
I've just been looking into this myself, and got directed to here. I'm personally tempted to go with option two, because the alternative is messy. Ronnie's version is nice, but unfortunately doesn't take into account cultures with different FirstDayOfWeeks.
Using Reflector, we can see how it's done internally:
...
DateTime visibleDate = this.EffectiveVisibleDate();
DateTime firstDay = this.FirstCalendarDay(visibleDate);
...
private System.Globalization.Calendar threadCalendar =
DateTimeFormatInfo.CurrentInfo.Calendar;
private DateTime EffectiveVisibleDate()
{
DateTime visibleDate = this.VisibleDate;
if (visibleDate.Equals(DateTime.MinValue))
{
visibleDate = this.TodaysDate;
}
if (this.IsMinSupportedYearMonth(visibleDate))
{
return this.minSupportedDate;
}
return this.threadCalendar.AddDays(visibleDate,
-(this.threadCalendar.GetDayOfMonth(visibleDate) - 1));
}
private DateTime FirstCalendarDay(DateTime visibleDate)
{
DateTime date = visibleDate;
if (this.IsMinSupportedYearMonth(date))
{
return date;
}
int num = ((int)
this.threadCalendar.GetDayOfWeek(date)) - this.NumericFirstDayOfWeek();
if (num <= 0)
{
num += 7;
}
return this.threadCalendar.AddDays(date, -num);
}
private int NumericFirstDayOfWeek()
{
if (this.FirstDayOfWeek != FirstDayOfWeek.Default)
{
return (int) this.FirstDayOfWeek;
}
return (int) DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek;
}
private bool IsMinSupportedYearMonth(DateTime date)
{
return this.IsTheSameYearMonth(this.minSupportedDate, date);
}
private bool IsTheSameYearMonth(DateTime date1, DateTime date2)
{
return (((this.threadCalendar.GetEra(date1) ==
this.threadCalendar.GetEra(date2)) &&
(this.threadCalendar.GetYear(date1) ==
this.threadCalendar.GetYear(date2))) &&
(this.threadCalendar.GetMonth(date1) ==
this.threadCalendar.GetMonth(date2)));
}
Sadly, the functionality is already there, we just can't get at it!
Mitchel,
Worked perfectly, thank you.
Started with a public variable
bool m_FirstDay = false
in the day_render function
if(m_FirstDay == false)
{
DateTime firstDate;
DateTime lastDate;
firstDate = e.Day.Date;
lastDate = firstDate.AddDays(41);
m_FirstDay = true;
}
I then had the visible date range of the asp.net calendar control. Thanks again.
see this one.
How to Remove the Last Week Of a Calendar

Resources