How can we specify custom date range with fullcalendar? - 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');
}
}

Related

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
}
}

node RRule check if rule day is today

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;
}

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.

Something Like setAsToday(date)?

With default view set to agendaWeek. If I load fullCalendar at 11:59PM the today day slot is not automatically updated after 12:00AM until I refresh the browser.
This is how I fixed it:
Call a function every 5 minutes (or any interval that suits your requirements)
$(function() {
var tInterval = 5*60*1000;
timelineInterval = window.setInterval(updateFcToday, tInterval); // Update timeline after every 5 minutes
});
Add a function like this to the page that contains your calendar:
function updateFcToday() {
var curTime = new Date();
if(curTime.getHours() == 0 && curTime.getMinutes() <= 5) // this five minutes is same interval that we are calling this function for. Both should be the same
{// the day has changed
var todayElem = $(".fc-today");
todayElem.removeClass("fc-today");
todayElem.removeClass("fc-state-highlight");
todayElem.next().addClass("fc-today");
todayElem.next().addClass("fc-state-highlight");
}
}

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