How to find today's date in DateTimePicker JavaScript? - javascript

I'm using the following javascript: http://xdsoft.net/jqplugins/datetimepicker , and I want to achieve simple effect - when User selects today's day, it should show him only hours available from now until the end of the day, the previous time should be disabled. But when he choses any other day in the future - then the whole time should be available. I wrote the following function in JS:
<script>
var today = new Date();
var dd = today.getDate();
alert(dd);
var logic = function( currentDateTime ){
if( currentDateTime.getDay()==dd ){
this.setOptions({
formatTime:'g:i A',
format: 'd/m/Y h:i A',
minDate:'+1970/01/02',//today
minTime: //I don't know yet how to implement the current time
});
}else
this.setOptions({
formatTime:'g:i A',
format: 'd/m/Y h:i A',
minDate:'+1970/01/02'//today
});
};
jQuery('#datetimepicker').datetimepicker({
onChangeDateTime:logic,
onShow:logic
});
</script>
The problem is that that line:
currentDateTime.getDay()==dd
doesn't work, because in my case dd equals todays day of the month (e.g. 25), and currentDateTime.getDay() checks current day of the week (e.g. for saturday it's 6). Is there anyone who could help me with that issue? I know there are some other available solutions (other datetime pickers), but I cannot find any other that is as simple and elegant as this. Thanks!

You want to use getDate() which returns the day in the month, instead of getDay() which returns the day in the week.
You should read the Date reference page.

Related

Bootstrap 3 datepicker - minDate and maxDate

http://eonasdan.github.io/bootstrap-datetimepicker/
Hi
I am trying to use the min max date options but not sure how to use it as the documentation doesn't provide example code.
I found on stackoverflow that you can do this:
minDate: moment()
But that throws an error that moment is not defined.
I am guessing it can't find the moment.js which is included on the page otherwise the plugin wouldn't work.
What I am trying to achieve is to disable 10 days before the current day and show 30 days from the current day.
Thanks
Here is the code (I have removed everything except whats important to simply show the code):
window[ns] = window[ns] || {};
(function ($, moment, app) {
'use strict';
// Private Methods
var nameSpace = 'global',
globalDataObject = null,
notifyRenderCallbacks = function (pageName) {
if ($('.js-calendar').length) {
$('.js-calendar').datetimepicker({
format: 'DD MMMM YYYY',
dayViewHeaderFormat: 'MMMM YYYY',
icons: {
next: 'icon icon-chevronright',
previous: 'icon icon-chevronleft'
},
enabledDates: moment().add(30, 'days')
});
}
},
// If this module requires global data
app.register(nameSpace, initialize);
}(jQuery, moment, window[ns] || {}));
To answer my question. The framework used required you to add moment to a config file otherwise it would not allow to use http://momentjs.com/ or any other JS - spoke to the person who set up the framework and they did it for security reasons.
Kasun's answer is correct but a better way to do this is to use Moment.js since datetimepicker is using this JS.
So to answer the 2nd part which is to disable 10 days before the current day and show 30 days from the current day you need to set the options as below. I didn't need to do the 10 days before but wanted only a set number of days to be available to select. I've added comments to make things clear but they shouldn't be there.
$mydatepicker.datetimepicker({
minDate: moment(), // Current day
maxDate: moment().add(30, 'days'), // 30 days from the current day
viewMode: 'days',
format: 'DD MMMM YYYY',
dayViewHeaderFormat: 'MMMM YYYY',
});
What the above will do is enable all the days between minDate and maxDate.
You could also directly enter the date range:
$mydatepicker.datetimepicker({
minDate: moment("12/01/2015"),
maxDate: moment("12/30/2015"),
viewMode: 'days',
format: 'DD MMMM YYYY',
dayViewHeaderFormat: 'MMMM YYYY',
});
And this will disable all days before and after the dates you entered into moment().
This is not part of the question but I wanted to display the current day in the input value when the calendar loaded but it wouldn't, instead it would show the placeholder text. I think its because of the use if minDate so I simply used jQuery to replace the value of the input.
$datepickerInput.val(moment());
var todayDate = new Date().getDate();
$('#element').datetimepicker({
timepicker:false,
formatDate:'Y/m/d',
minDate: new Date(),
maxDate: new Date(new Date().setDate(todayDate + 30))
});
By using this example you can give option to user to select date between today and next 30 days without using momentjs. You can provide value of minDate and maxDate accoording to you. For an example if you want to give options in between last 30 days to next 30 days, so set
minDate: new Date(new Date().setDate(todayDate - 30))
maxDate: new Date(new Date().setDate(todayDate + 30))
Just give this way, using JavaScript Date Object:
minDate: (new Date()).getDate()
For disable
$("#editreservation_to").datetimepicker({minDate:-1,maxDate:-2}).attr('readonly','readonly');
For Enable
$("#editreservation_to").datetimepicker({minDate:false,maxDate:false}).removeAttr('readonly');

Set automatic firstday

I want to set up automatic value of prameter 'firstday' in the fullcalendar. I have to manualy set number 0-6.
I would like to implement function:
var fday=new Date()
document.write([fday.getDay()])
to
firstDay: **HERE**
But I don't know how.
I need it for calendar where people may subscribe for a prayer.
If you want to set the firstDay you can do:
var yourDate = // Let's assume here you have your Date Object
$('#calendar').fullCalendar({
firstDay: yourDate.getDay()
});
If you want to set the firstDay based on the current day:
$('#calendar').fullCalendar({
firstDay: moment().toDate().getDay()
});
Keep in mind you cannot use:
moment().startOf('week').isoWeekday()
Because
moment.js Sunday = 7
fullCalendar Sunday = 0

bootstrap-datetimepicker hours and minutes not defaulted to 00:00

how to set default time hours and minutes as 00:00 but if i pick hours and minutes picked value should come. My issue is current time is coming by default and current date is highlighting. i am using bootstrap date time picker
By using option i am changing like this but not working. if i change format like dd/mm/yyyy 00:00 all the time it is showing 00:00 even if i pick hours and minutes. pls help me to solve this issue
My code is
$(document).ready(function(){
$('#datetimepicker1').datetimepicker({
$('#datetimepicker1').datetimepicker("setHours",'00' );
});
$('#datetimepicker2').datetimepicker({
$('#datetimepicker2').datetimepicker("setMinutes",'00' );
});
Perhaps you can try initializing the date picker with a default date, instead of trying to explicitly set the values. (I'm not sure datetimepicker even has setHours/minutes methods.) For example, you might do something like:
var d = new Date();
// hours, minutes, seconds
d.setHours(0, 0, 0);
$('#datetimepicker1').datetimepicker({
defaultDate: d
});
Hopefully this works for you or at least points you in the right direction! :)
What's jquery you using? Is it here ?
You should try to use DateTimePicker jQuery. It's simple and very good.
jQuery('#datetimepicker').datetimepicker({
format : 'd/m/Y H:i',
defaultTime:'00:00',
formatTime:'H:i'
});

CalendarExtender saying the wrong date is selected, possibly timezone related

I have a page with a TextBox and a CalendarExtender that is supposed to allow me to detect what date is selected. However, this is reporting the date that isn't selected.
<asp:TextBox ID="tbEffectiveDate" runat="server"
CssClass="input-small"
MaxLength="10"
Text='<%# Bind("NewEffectiveDate", "{0:MM/dd/yyyy}") %>'>
</asp:TextBox>
<ajaxToolkit:CalendarExtender ID="atkEffectiveDate" runat="server"
FirstDayOfWeek="Sunday"
TargetControlID="tbEffectiveDate"
Format="MM/dd/yyyy"
OnClientDateSelectionChanged="CheckForSunday">
</ajaxToolkit:CalendarExtender>
Essentially I'm making sure the user has selected a Sunday, but when I select a day on the calendar, the JavaScript says it is a day before. I'm perplexed.
function CheckForSunday(sender, args) {
var selectedDate = new Date();
selectedDate = sender.get_selectedDate();
// Both of these show the date before the date was selected
alert(sender.get_selectedDate());
if (selectedDate.getDay() != 0) {
// not a Sunday
var sunday = selectedDate;
// calculated the nearest Sunday
sunday.setDate(selectedDate.getDate() - selectedDate.getDay());
sender.set_selectedDate(sunday);
// tell the user that the date wasn't a Sunday
// and that the previous Sunday was selected.
$("#must-be-sunday").modal("show");
}
}
For example, if I select a Sunday, such as May 5th:
Then at the line alert(sender.get_selectedDate());, it displays
This is saying Saturday, May 4th is selected instead of May 5th. Since in my locale, we are -0700 and this is displaying 7 hours before midnight on the 5th, I'm guessing this has something to do with the timezone.
Does anyone know what may be causing this and how to fix it so it doesn't work with the time and only the date selected?
As usual, after writing everything out into a question on here, I've resolved my issue. This was indeed due to timezones, but still is very awkward. If someone has a better solution, I'd love to hear it.
Using getTimezoneOffset() and the solution from How to add 30 minutes to a JavaScript Date object?, I created a calculation to fix this.
var selectedDate = sender.get_selectedDate();
// get the timezone offset in minutes
var timeOffsetMinutes = selectedDate.getTimezoneOffset();
// Convert minutes into milliseconds and create a new date based on the minutes.
var correctedDate = new Date(selectedDate.getTime() + timeOffsetMinutes * 60000);
This corrected my issue and I get the date needed.
You right that the problem due to timezones as CalendarExtender use UTC dates for each day cell value. If you want to check day of week selected you may use Date.getUTCDay() function instead of the Date.getDay() and getUTCDate() instead of getDate() in OnClientDateSelectionChanged handler.

JavaScript date objects UK dates

I have the following code
datePicker.change(function(){
dateSet = datePicker.val();
dateMinimum = dateChange();
dateSetD = new Date(dateSet);
dateMinimumD = new Date(dateMinimum);
if(dateSetD<dateMinimumD){
datePicker.val(dateMinimum);
alert('You can not amend down due dates');
}
})
dateSet = "01/07/2010"
dateMinimum = "23/7/2010"
Both are UK format. When the date objects are compared dateSetD should be less than dateMinimumD but it is not. I think it is to do with the facts I am using UK dates dd/mm/yyyy. What would I need to change to get this working?
The JavaScript Date constructor doesn't parse strings in that form (whether in UK or U.S. format). See the spec for details, but you can construct the dates part by part:
new Date(year, month, day);
MomentJS might be useful for dealing with dates flexibly. (This answer previously linked to this lib, but it's not been maintained in a long time.)
This is how I ended up doing it:
var lastRunDateString ='05/04/2012'; \\5th april 2012
var lastRunDate = new Date(lastRunDateString.split('/')[2], lastRunDateString.split('/')[1] - 1, lastRunDateString.split('/')[0]);
Note the month indexing is from 0-11.
var dateString ='23/06/2015';
var splitDate = dateString.split('/');
var month = splitDate[1] - 1; //Javascript months are 0-11
var date = new Date(splitDate[2], month, splitDate[0]);
Split the date into day, month, year parts using dateSet.split('/')
Pass these parts in the right order to the Date constructor.
Yes, there is problem with the date format you are using. If you are not setting a date format the default date that is used is 'mm/dd/yy. So you should set your preferred date formate when you create it as following when you create the date picker:
$(".selector" ).datepicker({ dateFormat: 'dd/mm/yyyy' });
or you can set it later as:
$.datepicker.formatDate('dd/mm/yyyy');
When you try to create a date object:
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Example:
dateSetD = new Date(dateSet.year, dateSet.month, dateSet.day);
Note: JavaScript Date object's month starts with 00, so you need to adjust your dateset accordingly.

Categories

Resources