node RRule check if rule day is today - datetime

I am using 'rrule.js' library in node to parse my RRule. I would like to know if current day is same as rule day. It works on most cases but not all. I also use moment.js to compare. The issue is in "rule.after()". It should include the current day but it doesn't.
function checkIfToday(rruleStr){
var RRule = require('rrule').RRule;
var moment = require('moment');
var rule = RRule.fromString(rruleStr);
// Convert all dates into UTC before comparison
var todayutc = moment().utc(); // today in UTC
var nextOccurrence = rule.after(todayutc,inc=true); // next rule date including today
var nextOccurutc = moment(nextOccurrence).utc(); // convert today into utc
var match = moment(nextOccurutc).isSame(todayutc, 'day'); // check if 'DAY' is same
return match;
}
Any idea what's the best way to do this.
Thanks.

This worked for me. Try setting the time of todayutc back to the beginning of the day using moment's startOf method:
function checkIfToday(rruleStr){
var RRule = require('rrule').RRule;
var moment = require('moment');
var rule = RRule.fromString(rruleStr);
// Convert all dates into UTC before comparison
var todayutc = moment().utc().startOf('day'); // today in UTC
var nextOccurrence = rule.after(todayutc, true); // next rule date including today
var nextOccurutc = moment(nextOccurrence).utc(); // convert today into utc
var match = moment(nextOccurutc).isSame(todayutc, 'day'); // check if 'DAY' is same
return match;
}

Related

DateTime in UTC not converting to Local

I'm receiving a DateTime response from API that's sets the timezone to UTC.
But when I try to convert the received data using toLocal() it doesn't convert.
my local time is HKT
here's my code.
//TIME DIFFERENCE
getNotificationDate(DateTime date) {
date = date.toUtc();
final convertedDate = date.toLocal();
final dateNow = DateTime.now();
print('TIMENOW: ' + dateNow.toString());
print('TIMENOTIFC: ' + convertedDate.toString());
final difference = dateNow.difference(convertedDate);
print('DIFFERENCE: ' + difference.toString());
return getDurationFormat(difference);
}
EDIT:
date is the DateTime I'm receiving from the API. which is in UTC timezone.
I used print('TIMEZONENAME: ' + date.timeZoneName; and it automatically sets the timezone to HKT. that's why it does nothing when I try to use date.toLocal()
Flutter gave us the easiest way to convert it.
You just need to pass utc: true while parsing your date.
var dateTime = DateFormat("yyyy-MM-dd HH:mm:ss").parse(dateUtc, true);
var dateLocal = dateTime.toLocal();
Input:
Assume my TimeZone : +05:30
UTC Date -> 2020-02-12 23:57:02.000
Output:
Local Date -> 2020-02-12 18:27:02.019660
// you have time in utc
var dateUtc = DateTime.now().toUtc();
print("dateUtc: $dateUtc"); // 2019-10-10 12:05:01
// convert it to local
var dateLocal = dateUtc.toLocal();
print("local: $dateLocal"); // 2019-10-10 14:05:01
Can you see the difference in hours, in utc it is 12 and locally it is 14.
Firstly, convert your Sting to DateTime.
> DateTime dateTime = DateTime.parse(json['pickUpTime']);
Secondly, add timeZoneOffSet to your converted date time it will convert utc to your local time.
> dateTime = dateTime.add(DateTime.parse(json['pickUpTime']).timeZoneOffset);
Final Code
DateTime dateTime = DateTime.parse(json['pickUpTime']);
dateTime = dateTime.add(DateTime.parse(json['pickUpTime']).timeZoneOffset);
You can try this code:
getNotificationDate(DateTime date) {
date = DateTime.utc(date.year,date.month,date.day,date.hour,date.minute,date.second);;
final convertedDate = date.toLocal();
final dateNow = DateTime.now();
print('TIMENOW: ' + dateNow.toString());
print('TIMENOTIFC: ' + convertedDate.toString());
final difference = dateNow.difference(convertedDate);
print('DIFFERENCE: ' + difference.toString());
return getDurationFormat(difference);
}
I've done something like this.
String dateTimeFormatter(String dateTime, {String? format}) {
return DateFormat(format ?? 'yyyy/MM/dd, hh:mm a')
.format(DateTime.parse(dateTime).toLocal())
.toString();
}
just pass the format which you want to display in your app.
If somebody needs to parse a UTC timestamp in isoformat, for example something like this:
>>> from datetime import datetime
>>> datetime.utcnow().format()
'2021-07-20T19:35:19.769891'
Then you can parse this and convert this to local time by
DateTime parseDatetimeFromUtc({required String isoFormattedString}){
var dateTime = DateTime.parse(isoFormattedString + '+00:00');
return dateTime.toLocal();
}
The '+00:00' is append here as the timezone information part which I do not send over my API to save some bytes. Maybe this helps someone who is in the same situation.
Of course you do not need this hardcoded suffix if you use a timezone aware timestamp in your backend:
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2021-07-20T19:42:36.538195+00:00'
For those who parsing TimeStamp from Firestore.
*sentAt is Timestamp
String timeToDate = widget.sentAt.toDate().toString();
var dateTime = DateFormat("yyyy-MM-dd HH:mm:ss").parse(timeToDate, true);
var dateLocal = dateTime.toLocal();
this is how i converted to my required time .which was showing as
I/flutter ( 5709): 16 Apr 08:30 PM 2021
when using the
var date=DateFormat("dd MMM hh:mm a y").format(DateTime.fromMillisecondsSinceEpoch(start*1000));
print(date);
but after using this code i got my right time
var date=DateFormat("dd MMM hh:mm a y").format(DateTime.fromMillisecondsSinceEpoch(start*1000).toUtc());
print(date);
which is
I/flutter ( 5709): 16 Apr 03:00 PM 2021
I tried several examples and forums, but it kept getting me the incorrect date time for my zone, The only way I made it work correctly was by using the GMT package
var nowLocal = DateTime.now();
print("toUtc: ${nowLocal.toUtc()}");
print("toLocalDateTime ${nowLocal.toLocalDateTime()}");
print("toLocal ${nowLocal.toLocal()}");
print("toIso8601String ${nowLocal.toIso8601String()}");
final timeZoneOffsetInHours = DateTime.now().timeZoneOffset.inHours;
final nowGMT = await GMT.now();
print("GMT: $nowGMT");
final nowActual = nowGMT?.add(Duration(hours: timeZoneOffsetInHours));
print("nowActual $nowActual");
Two solutions I implemented
var date = DateFormat("yyyy-MM-ddTHH:mm:ss").parse(json, true);
var dateLocal = date.toLocal();
Other solutions add "Z"
You need to indicate a timezone to DateTime.parse, otherwise it assumes local time. From the dartdoc:
var date = DateTime.parse("${dateString}Z").toLocal();
var dateFormat = date2.toLocal();
Install intl package from pub.dev
add following line :
import 'package:intl/intl.dart';
You can make an extension like below so it will be very helpful and easy to use anywhere in a whole project.
//just make sure you have passed the right date format of utc("yyyy-MM-dd HH:mm:ss"). I have passed by default my format.
//for example
// 2020-11-25 24:12:36 -> "yyyy-MM-dd HH:mm:ss"
DateTime localDate=utcDateTime.toLocalDateTime();
//for different formats you can pass your own dateFormat for utcDate like below:
// 20-11-25 24:12:36 -> "yy-MM-dd HH:mm:ss"
DateTime localDate=utcDateTime.toLocalDateTime("yy-MM-dd HH:mm:ss");
extension DateTimeExtension on DateTime {
DateTime toLocalDateTime({String format = "yyyy-MM-dd HH:mm:ss"}) {
var dateTime = DateFormat(format).parse(this.toString(), true);
return dateTime.toLocal();
}
}
convert utc number to DateTime:
DateTime utcToDateTime(int utc) {
return DateTime(1970, 1, 1).add(Duration(seconds: utc));
}
//test
DateTime d = utcToDateTime(1649297709);
print(d);

Google Sheet converting wrong the date

I vave a column that i only write numbers in the cells. Like for example:
I write 15022019 then i go to number formats and choose date. So the number is converted to 15/02/2019.
But i don't need everytime when i write a number make the change to date format. I need it automatically. So i found this script:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var column = sheet.getRange("D3:D31");
column.setNumberFormat("dd/mm/yyy");
It work. But is changing the numbers to date format incorrectly. If i write 14022019 its convert to 24/12/40290, and not in 14/02/2019(how i expected).
Why that?
Just in manually way it converts rightly. My location is Brazil.
Can someone say me what i'm doing wrong?
Edit 1:
I need it to convert to date automatically each time i fill a cell with the date. My range date will be always D3:D31. I tried modify the lines bellow:
function convertnumbertodate(crange){
// establish spreadsheet credentials
var ss1=SpreadsheetApp.getActive();
var sh1=ss1.getActiveSheet();
// get the range so that rows and columns can be calculated
var rg1=sh1.getRange(crange);
And in the place of (crange) i put D3:D31 to try to make the conversion to date automatically. Look bellow:
function convertnumbertodate(crange){
// establish spreadsheet credentials
var ss1=SpreadsheetApp.getActive();
var sh1=ss1.getActiveSheet();
// get the range so that rows and columns can be calculated
var rg1=sh1.getRange(D3:D31);
But when i run the function convertnumbertodate it reports error.
Can you help me how make it convert to date automatically?
Thank you
Edit 2:
Just made what you did:
function convertnumbertodate() {
// establish spreadsheet credentials
var editedCell;
var sh1=ss1.getActiveSheet();
// get the range so that rows and columns can be calculated
var rg1=sh1.getRange(D3:D31);
// get number of columns
var numColumns = rg1.getNumColumns();
// if more than one column chosen, stop the process.
if (numColumns !=1){
//Logger.log("DEBUG: Number of columns in range = "+numColumns); // DEBUG
var message = "Too Many Columns; one column only";
return message;
}
etc.
I deleted the crange and put my range D3:D31
Also made it run OnEdit: var editedCell;
But when i run, it says thats have an error in the line var rg1=sh1.getRange(D3:D31);
Problem
The OP enters 14022019 in an unformated cell. When the cell is formatted as a date, the value returned is 24 December 40290; the OP expected the date to be 14 February 2019.
Solution
- 1: format the cell as a date before data entry.
- 2: enter number with separators, such as 14/02/2019 or 14-02-2019
Explanation
When the OP types "14022019" into an unformatted cell, they intend that the input should be treated as a date (14 February 2019). However Google treats the contents at face value; there is no inference about date/time. So, when the cell is subsequently formatted as date, the raw value is converted to a date and the cell displays 24 December 40290.
The reason is that the Google Time Epoch began on 31 December 1899 00:00:00 (as opposed to the Unix Time Epoch, which is used by Javascript, which began on January 1, 1970 00:00:00). Secondly, Google measures date-time in days (as opposed to the Unix Epoch that measures elapsed seconds).
This is (roughly) how Google converts 14,022,019 to 24 December 40290.
14,022,019 "days", at a rough average of 365.245 days per year = approximately 38390.7 years.
Add on 1899 for the Google Epoch. Running total = 40289.7 years. (roughly mid September 40290)
Allow for adjustments for leap years 101.795 days = 0.3 (101.795/365.245); running total = 40290 years. (roughly 24 December 40290)
Note#1: there is a further complication.
The way that Sheets and Apps Script handle "dates" are very different.
Sheets: the "date" unit is 1 day; The base date is 1899-12-30 0:00:00, getting the timezone from the spreadsheet settings.
Apps Script (being based on JavaScript): the "date" unit is 1 millisecond. The base date is 1970-1-1 00:00:00 UTC.
Reference/Credit: Rubén
Note#2: My reference for the Google Epoch is (https://webapps.stackexchange.com/a/108119/196152)
Note#3: Broadly date/time conversions are based on 3,600 seconds per hour, 86,400 seconds per day, 31,556,926 second per year and 365.24 days per year.
UPDATE - 20 Feb 2019
The OP asks, quite rightly, "so how do I convert the existing cells?"
The code to make the conversion is straightforward:
- convert the number to a string
- slice the string into components for Day, Month and Year
- use the components to create a new date
- update the cell with the date
The range to be converted is an potential issue. What is the range, is the range always the the same size, etc? The following code enables an interface for the user to choose a range. The range can then be converted. Arguably this element wasn't essential, but does provide a more flexible, if not elegant, solution.
Code.gs
function onOpen(){
SpreadsheetApp.getUi()
.createMenu("Date Convert")
.addItem("Convert", "selRange")
.addToUi();
}
function selRange()//run this to get everything started. A dialog will be displayed that instructs you to select a range.
{
var output=HtmlService.createHtmlOutputFromFile('pickRange').setWidth(300).setHeight(200).setTitle('Convert to dates');
SpreadsheetApp.getUi().showModelessDialog(output, 'Convert Numbers to Dates');
}
function selCurRng()
{
var sso=SpreadsheetApp.getActive();
var sh0=sso.getActiveSheet();
var rg0=sh0.getActiveRange();
var rng0A1=rg0.getA1Notation();
rg0.setBackground('#FFC300');
return rng0A1;
}
function clrRange(range)
{
var sso=SpreadsheetApp.getActive();
var sh0=sso.getActiveSheet();
var rg0=sh0.getRange(range);
rg0.setBackground('#ffffff');
}
function convertnumbertodate(crange){
// establish spreadsheet credentials
var ss1=SpreadsheetApp.getActive();
var sh1=ss1.getActiveSheet();
// get the range so that rows and columns can be calculated
var rg1=sh1.getRange(crange);
// get number of columns
var numColumns = rg1.getNumColumns();
// if more than one column chosen, stop the process.
if (numColumns !=1){
//Logger.log("DEBUG: Number of columns in range = "+numColumns); // DEBUG
var message = "Too Many Columns; one column only";
return message;
}
// get the first row and the number of rows
var rowqty = 1;
var rownum = rg1.getRow();
// Logger.log("DEBUG: first row = "+rownum);//DEBUG
var rowqty = rg1.getNumRows();
// Logger.log("DEBUG: Number of rows = "+rowqty); //DEBUG
// get the values - different syntax for a single cell vs range
if (rowqty !=1){
// Multiple cells - uset GetValues
var rangevalues = rg1.getValues();
}
else {
// single cell, use getValue
var rangevalues = rg1.getValue();
}
//Logger.log("DEBUG: Values = "+rangevalues); //DEBUG
// create array for temporary storage
var newvalues = [];
// loop through the values
for (var i=0; i< rowqty; i++){
// different treatment for single cell value
if (i!=0 && rowqty !=1){
// multiple cells
var nstring = rangevalues[i].toString();
}
else {
// single value cell
var nstring = rangevalues.toString();
}
Logger.log("DEBUG: Value of the string is = "+nstring); //DEBUG
// slice the string in day, month and year
var daystring = nstring.slice(0, 2);
var monthstring = nstring.slice(2, 4);
var yearstring = nstring.slice(4, 8);
//calculate the date
var pubdate = new Date(yearstring, monthstring - 1, daystring);
//Logger.log("DEBUG: the date is "+pubdate); //DEBUG
// push the value onto the aray
newvalues.push([pubdate]);
}
// set the value(s)
if (rowqty !=1){
// Multiple cells - uset GetValues
rg1.setValues(newvalues)
}
else {
// single cell, use getValue
rg1.setValue(newvalues);
}
//rg1.setValues(newvalues);
var message = "Update complete";
rg1.setBackground('#ffffff');
return message;
}
pickRange.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var grange='';
function selectRange()
{
$('#btn1').prop('disabled',true);
$('#btn2').prop('disabled',false);
google.script.run
.withSuccessHandler(setResponse)
.selCurRng();
}
function setResponse(r)
{
grange=r;
var msg='Selected range: ' + r+". Ready to convert";
$('#instr').css('display','none');
$('#rsp').text(msg);
}
function convert2date()
{
$('#btn1').prop('disabled',false);
$('#btn2').prop('disabled',false);
google.script.run
.withSuccessHandler(setResponse02)
.convertnumbertodate(grange);
}
function setResponse02(q)
{
qnumber=q;
var msg= q;
$('#instr').css('display','none');
$('#rsp').text(msg);
}
function clearAndClose()
{
google.script.run.clrRange(grange);
google.script.host.close();
}
console.log('My Code');
</script>
</head>
<body>
<div id="rsp"></div>
<div id="instr">Select range - <b>One column limit</b></div>
<br/>
<input type="button" id="btn1" value="1 - Select a range" onClick="selectRange();" />
<br />
<input type="button" id="btn3" value="2 - Convert numbers to dates" onClick="convert2date();" />
<br />
<input type="button" id="btn2" value="close" onClick="clearAndClose();"; disabled="true" />
</body>
</html>
Credit
//Prompt user for range in .gs function, pass array to html script and re-focus on the HTML dialog
//credit answer by Cooper - https://stackoverflow.com/a/45427670/1330560
ADDENDUM
If the range in which pseudo-dates are entered is know, and is non-changing, then the code to manage it is simplified
function onEdit(e) {
// establish spreadsheet credentials
var ss1 = SpreadsheetApp.getActive();
var sh1 = ss1.getActiveSheet();
// get the onEdit parameters
var debug_e = {
authMode: e.authMode,
range: e.range.getA1Notation(),
source: e.source.getId(),
user: e.user,
value: e.value,
oldValue: e.oldValue
};
//Logger.log("AuthMode: "+debug_e.authMode+"\n, Range: "+debug_e.range+"\n, source: "+debug_e.source+"\n, user: "+debug_e.user+"\n, value: "+debug_e.value+"\n, old value: "+debug_e.oldValue);
// Note the range for data entry is known and fixed.
// it is "D3:D31"
// Target range for converting numbers to dates
// set the column
var column = 4; // column D
// get the first row and the number of rows
var rowqty = 29;
var rowfirst = 3;
var rowlast = 31;
//Logger.log("DEBUG: first row = "+rowfirst+", last row = "+rowlast+", number of rows = "+rowqty);//DEBUG
// get detail of the edited cell
var editColumn = e.range.getColumn();
var editRow = e.range.getRow();
//Logger.log("DEBUG: edited column = "+editColumn+", edited row "+editRow);//DEBUG
//test if the edited cell falls into the target range
if (editColumn == 4 && editRow >= rowfirst && editRow <= rowlast) {
// the edit was in the target range
var nstring = e.value.toString();
//Logger.log("DEBUG: Value of the string is = "+nstring); //DEBUG
// slice the string in day, month and year
var daystring = nstring.slice(0, 2);
var monthstring = nstring.slice(2, 4);
var yearstring = nstring.slice(4, 8);
//calculate the date
var pubdate = new Date(yearstring, monthstring - 1, daystring);
//Logger.log("DEBUG: the date is "+pubdate); //DEBUG
e.range.setValue(pubdate)
} else {
//Logger.log("DEBUG: Nothing to see here; this cell not in the target range");//DEBUG
}
}

How to compare two dates with each other in Flex?

I have a standard ISO8601 date string:
2004-02-12T15:19:21+00:00
I want to know if this date is older than 10 minutes ago in Flex. So basically:
if ("2004-02-12T15:19:21+00:00" > current_time - 10mins) {
// do whatever
}
What would the syntax be in Flex? I'm basically stuck at trying to convert the string into a Flex Date Object without parsing it character by character.
If you don;t care about the timezone i.e. the date string is in the same timezone as where you are running the application then this should work.
var date:Date = DateFormatter.parseDateString("2004-02-12T15:19:21+00:00");
var now:Date = new Date();
var tenMinAgo:Number = now.time - 1000*60*10;
if (date.time < tenMinAgo) {
trace("More than 10 min ago");
}

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 can we specify custom date range with fullcalendar?

I want to use fullcalendar with custom date range for ex. it should display view for particular date range like from 15th April to 4th May(Spans between two months).
Any suggestions?.
you can call this function to gt events in date range. but this will bring you only 30 days evnt. if you pass dates like '01-may-2013' to 15-June-2013' then it will show data from 01-may2013 to 30st may 2013. Lt me know if you can find any clue for this issue.
function GetAgendaEvents(datefrom, dateTo) {
var fromDate = new Date($("#from").val());
var toDate = new Date($("#to").val());
if (fromDate.getTime() <= toDate.getTime()) {
$('#fullcal').fullCalendar('removeEvents').fullCalendar('addEventSource', events);
$('#fullcal').fullCalendar('refetchEvents');
var filteredEvent = $('#fullcal').fullCalendar('clientEvents', function (event) {
return event.start >= fromDate && event.start <= toDate;
});
$('#fullcal').fullCalendar('gotoDate', fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
$('#fullcal').fullCalendar('changeView', 'agenda'/* or 'basicDay' */);
$('#fullcal').fullCalendar('removeEvents').fullCalendar('addEventSource', filteredEvent);
$('#fullcal').fullCalendar('refetchEvents');
}
}

Resources