I have a code snippet which gives me the date on selecting from Calender of JSdatepicker Library.
I am looking for a way to get the name of weekday with selected date ex: monday, tuesday etc...
Below is the usage of jsDatepicker:
<script type="text/javascript">
window.onload = function(){
new JsDatePick({
useMode:2,
target:"inputField1",
dateFormat:"%Y-%m-%d",
cellColorScheme:"beige"
});
};
</script>
I checked out the documentation given in jsDatePicker But didn't got anything.
Can somebody help?
I also tried using jQuery Datepicker, but it doesn't work at all, below is the jQuery datepicker code:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
For both cases my inout field to select and display date is:
<input type="text" id="datepicker"/>
If you want to use JsDatePick, here's one way to do so:
// Save returning object to variable
var dateSelector = new JsDatePick({
useMode:2,
target:"inputField1",
dateFormat:"%Y-%m-%d",
cellColorScheme:"beige"
});
// Use setOnSelectedDelegate to capture clicks
dateSelector.setOnSelectedDelegate(function(){
// Get selected day from plug-in
var day = dateSelector.getSelectedDay();
// Create a JS native Date
var date = new Date(day.year, day.month, day.day);
// Get the day of the week (0 is Sunday)
var dayOfTheWeek = date.getDay();
// For demonstration purposes, place a string into input field
var inputField = document.getElementById("inputField1");
var dayOfTheWeekStr = '';
switch (dayOfTheWeek) {
case 0:
dayOfTheWeekStr = 'Sunday';
break;
case 1:
dayOfTheWeekStr = 'Monday';
break;
case 2:
dayOfTheWeekStr = 'Tuesday';
break;
default:
dayOfTheWeekStr = 'Wed.-Sat.';
break;
}
inputField.value = dayOfTheWeekStr;
});
Here's a JSFiddle.
For jquery datepicker here's fiddle
$(function() {
var dt = $("#datepicker" ).datepicker({
onSelect: function (dt) {
var wa = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var nd = new Date(Date.parse(dt));
$(this).val(wa[nd.getDay()]+', '+dt);
}
});
});
Related
With this code, I able to get selected date as unix.
jsfiddle
function getValue() {
var date = $('#example').data("DateTimePicker").date();
if( date ){
alert(date.unix());
}
}
How about PersianDate, I want to get selected date as unix.
jsfiddle
You can do it by using getState method on persianDatepicker instance, like this:
var pd = $('#example').persianDatepicker({
autoClose: true,
// other options
});
function showUnix() {
const state = pd.getState();
alert(state.selected.unixDate);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://babakhani.github.io/PersianWebToolkit/doc/lib/persian-date/dist/persian-date.js"></script>
<script src="https://babakhani.github.io/PersianWebToolkit/doc/lib/persian-datepicker/dist/js/persian-datepicker.js"></script>
<link href="https://unpkg.com/persian-datepicker#latest/dist/css/persian-datepicker.min.css" rel="stylesheet" />
<input type="text" id="example" class="initial-value-type-example inline-example leapyear-algorithmic">
<button onclick="showUnix()">show unix</button>
I am trying to dynamically disable date (jquery datepicker) which is already in database. I have done static method in that I am able to achieve goal but not getting success in dynamic approach
<script language="javascript">
$(document).ready(function () {
var getfromdb = #Html.Raw(#ViewBag.bookdate);
var result = '\'' + getfromdb.toString().split(',').join('\',\'') + '\'';
var disableddates = [result];
var newdisableddates = ['17/10/2017','18/10/2017','19/10/2017','22/10/2017','23/10/2017','24/10/2017','25/10/2017']; // Static Approach
$("#txtFromdate").datepicker({
minDate: 0,
beforeShowDay: DisableSpecificDates,
dateFormat: 'dd/mm/yy'
});
$("#txtTodate").datepicker({
minDate: 0,
beforeShowDay: DisableSpecificDates,
dateFormat: 'dd/mm/yy'
});
function DisableSpecificDates(date) {
var string = jQuery.datepicker.formatDate('dd/mm/yy', date);
return [disableddates.indexOf(string) == -1];
}
});
And here is my controller code:
List<string> getbookdate = new List<string>();
getbookdate = BookDate(id);
ViewBag.bookdate = JsonConvert.SerializeObject(getbookdate.ToList());
public List<string> BookDate(int? id)
{
DateTime dt = System.DateTime.Now.Date;
var getbookdate = (from x in entity.BookingMasters
join
y in entity.BookingDetails on x.BookingId equals y.BookingId
where x.ProductId == id && y.FromDate > dt && y.ToDate > dt
select new BookingModel { ProductId = x.ProductId.Value, FromDate = y.FromDate.Value, ToDate = y.ToDate.Value }).ToList();
List<string> allDates = new List<string>();
foreach (var r in getbookdate)
{
for (DateTime date = r.FromDate; date <= r.ToDate; date = date.AddDays(1))
{
allDates.Add(Convert.ToString(date.ToShortDateString()));
}
}
return allDates;
}
Disable doesn't work well with date picker. Try my plnkr.
https://embed.plnkr.co/h4RaeIKJVfj9IjyHREqZ/
It gets the datepicker on click and parses through the dates and data set given and if a match is found it removes the click event on it. and repeats on each render please see my plnkr link for html. Hope it helps
<!--Disable doesn't work well with date picker. Try this. Hope it helps-->
<!--Working example https://embed.plnkr.co/h4RaeIKJVfj9IjyHREqZ/ -->
<!--Code-->
<!--HTML PART-->
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script data-require="tether#*" data-semver="1.4.0" src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<link data-require="bootstrap#4.0.5" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
<link data-require="jqueryui#*" data-semver="1.12.1" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<script data-require="jqueryui#*" data-semver="1.12.1" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
</head>
<body class="container">
<h1>Hello User</h1>
<div class="box">
<div class="box-content">
<div class="row">
<div class="col-md-4">
<label>Date:</label>
<input type="text" id="date-picker-control" />
</div>
</div>
</div>
</div>
<script>
var element = $('#date-picker-control');
element.datepicker();
element.off('click').on('click', function() {
// Setup DatePicker
console.log('Update Date Picker');
// If user changes month or year, update date picker
// based on the date list you have
$("#ui-datepicker-div")
.find("div.ui-datepicker-header")
.find('a.ui-datepicker-next, a.ui-datepicker-prev')
.on('click', function() {
element.click();
});
// Get all available dates in current displayed dates
var availableDates = $("#ui-datepicker-div")
.find("table.ui-datepicker-calendar")
.find('td[data-handler="selectDay"]');
availableDates.filter(function(i) {
var targetDateElement = $(this);
//Get date parts
var year = +targetDateElement.data("year");
var month = targetDateElement.data("month") + 1; //JS fix
var day = +targetDateElement.find('a.ui-state-default').text();
var builtDate = month + '/' + day + '/' + year;
// you can substitute your json data
var targetDates = [
"10/2/2017", "10/6/2017", "10/8/2017"
];
$.each(targetDates, function(i, targetDate) {
// If builtDate match targetdate then turn click event oFF on that date
if (targetDate == builtDate) {
targetDateElement.css({
'border': '1px solid gray',
'background': 'darkgray',
'font-weight': 'bold',
'color': 'gray'
}).off('click');
}
});
});
});
</script>
</body>
</html>
Your original idea is in the right direction, but I think there's probably something weird going on with all the string conversion. I'd just pass through dates and compare with dates rather than all the stringy stuff:
I've written this quick test...
controller:
//Replace with however you get dates
ViewBag.DatesList = new List<DateTime>()
{
new DateTime(2018, 01, 01),
new DateTime(2018, 01, 02),
new DateTime(2018, 01, 03)
};
return View();
View:
<script language="javascript">
$(document).ready(function () {
var disableddates = [];
#foreach (DateTime date in ViewBag.DatesList)
{
//note JS month is zero-based for no good reason at all...
#:disableddates.push(new Date(#date.Year, #date.Month-1, #date.Day))
}
$("#txtFromdate").datepicker({
minDate: 0,
beforeShowDay: DisableSpecificDates,
dateFormat: 'dd/mm/yy'
});
$("#txtTodate").datepicker({
minDate: 0,
beforeShowDay: DisableSpecificDates,
dateFormat: 'dd/mm/yy'
});
function DisableSpecificDates(date) {
//filter array to find any elements which have the date in.
var filtereddates = disableddates.filter(function (d) {
return d.getTime() === date.getTime();
});
//return array with TRUE as the first (only) element if there are NO
//matching dates - so a matching date in the array will tell calling
//code to disable that day.
return [filtereddates.length == 0];
}
});
</script>
This appears to work for me.
I'm using bootstrap-datepicker and I have attached a listner to changeMonth event.
If I use one of setters listed here (e.g. setStartDate, setDatesDisabled, setDaysOfWeekHighlighted etc.) inside my listner, the picker view does not updates (month is unchanged). Everything works fine, if I do not use any datepicker's setter inside my listner.
Here a live sample showing the issue. In this example I'm trying to update dinamically hightlighted dates when the user changes months.
function getHighlighted(month){
var highlitedDays = [0, 1];
if( month % 2 == 0 ){
highlitedDays = [3, 4];
}
return highlitedDays;
}
$('#datepicker').datepicker({
daysOfWeekHighlighted: getHighlighted(new Date().getMonth())
}).on('changeMonth', function(e){
var month = e.date.getMonth();
var highlightedDays = getHighlighted(month);
// I use setDaysOfWeekHighlighted just as example
$('#datepicker').datepicker('setDaysOfWeekHighlighted', highlightedDays);
// Do something else
//...
});
$('#datepicker2').datepicker({
daysOfWeekHighlighted: getHighlighted(new Date().getMonth())
}).on('changeMonth', function(e){
console.log("I've just changed month to " + e.date.getMonth());
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<input type="text" class="form-control" id="datepicker">
<input type="text" class="form-control" id="datepicker2">
What am I missing?
I came across this issue when I aswered this question where I used setDatesDisabled inside changeMonth listner.
EDIT (after comments)
I've tried both using $(this) inside 'changeMonth' and assign my datepicker to a variable as shown here:
var dt = $('#datepicker').datepicker({
daysOfWeekHighlighted: getHighlighted(new Date().getMonth())
})
dt.on('changeMonth', function(e){
var month = e.date.getMonth();
var highlightedDays = getHighlighted(month);
// Neither using dt nor $(this) works
dt.datepicker('setDaysOfWeekHighlighted', highlightedDays);
// Do something else
//...
});
but the problem is still there.
#VincenzoC Please make sure you're using the latest version (1.7.1), this Fiddle demonstrates that it works https://jsfiddle.net/s35za9dr/
function getHighlighted(month){
var highlitedDays = [0, 1];
if( month % 2 == 0 ){
highlitedDays = [3, 4];
}
return highlitedDays;
}
$('#datepicker').datepicker({
daysOfWeekHighlighted: getHighlighted(new Date().getMonth()),
updateViewDate: false
}).on('changeMonth', function(e){
var month = e.date.getMonth();
var highlightedDays = getHighlighted(month);
// I use setDaysOfWeekHighlighted just as example
$('#datepicker').datepicker('setDaysOfWeekHighlighted', highlightedDays);
// Do something else
//...
});
$('#datepicker2').datepicker({
daysOfWeekHighlighted: getHighlighted(new Date().getMonth()),
updateViewDate: false
}).on('changeMonth', function(e){
console.log("I've just changed month to " + e.date.getMonth());
});
EDIT
Using any of the set* methods (e.g. setDatesDisabled) in the changeMonth, changeYear, changeDecade or changeCentury events will trigger an update which will cause the picker to revert back to the month in which the current view date occurs.
To prevent this you simply need to initiate the picker with the updateViewDate option set to false.
Problem: Your method update to current date whenever you change the date.
Solution: Try following code.
Remove your current on change method.
Add document Ready for initialize to current date and other is default.
<!DOCTYPE html>
<html>
<head>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<input type="text" class="form-control" id="datepicker">
<input type="text" class="form-control" id="datepicker2">
<script>
$( document ).ready(function() {
var startDate = $('#datepicker').datepicker('setStartDate', new Date());
});
$('#datepicker').datepicker().on('change', function(e){
// I use setStartDate just as example
var startDate = $('#datepicker').datepicker('setDaysOfWeekHighlighted', ['2016-04-29', '2016-04-30']);
// Do something else
//...
});
$('#datepicker2').datepicker().on('changeMonth', function(e){
console.log("I've just changed month to " + e.date.getMonth());
});
</script>
</head>
<body>
</body>
</html>
The website is supposed to display a message counting down to the tax day. I can't seem to get anything to display on the page. The scrollbar doesn't even show up with the color even though I put in the write code. Some advice please.
<!DOCTYPE HTML>
<html>
<head><meta charset="utf-8">
<title>TaxDay</title>
<script type="text/javascript">
<!-- Hide from old browsers
function scrollColor() {
styleObject=document.getElementsByTagName('html')[0].style
styleObject.scrollbarFaceColor="#857040"
styleObject.scrollbarTrackColor="#f4efe9"
}
function countDown() {
var today = new Date()
var day of week = today.toLocaleString()
dayLocate = dayofweek.indexOf(" ")
weekDay = dayofweek.substring(0, dayLocate)
newDay = dayofweek.substring(dayLocate)
dateLocate = newday.indexOf(",")
monthDate = newDay.substring(0, dateLocate+1)}
yearLocate = dayofweek.indexOf("2016")
year = dayofweek.substr(yearLocate, 4)
var taxDate = new Date ("April 16, 2017")
var daysToGo = taxDate.getTime()-today.getTime()
var daysToTaxDate = Math.ceil(daysToGo/(1000*60*60*24))
function taxmessage() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
taxDay.innerHTML = "<p style='font-size:12pt; font-
family:helvetica;'>Today is "+weekDay+" "+monthDate+" "+year+".
You have "+daysToTaxDate+" days to file your taxes.</p>"
}
}
//-->
</script>
The <div> id is taxDay if it's relevant. The body onLoad event handlers are scrollColor(); countDown(); and taxmessage().
you are not closing the countdown() function before the taxmessage() function - meaning that taxmessage is nested within countdown(). Also you do not have semicolons ";" after each line of the js. You should rewrite the code to either include the function of taxmessage() or close out countdown() first and call taxmessage with arguments passed to get the date variables.
check your console for errors
Need your help here again.
I don't have any code snippet for this.
Below is my problem description:
There are two text boxes .
In one text box user will enter any time in 24 hour format say 23:23 or 10:12..
Now I need to populate time in the second text box based on this entered time.
Second text box should display value after adding the 6 hours in 24 hours format to the entered time.i.e. should display 05:23 or 16:12 and so on.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$('#new_one').on('change',function (e) {
var first_time = $(this).val();
var arr = first_time.split(':');
var hrs = arr[0];
var new_hrs = parseInt(hrs)+6;
if(new_hrs>24)
new_hrs = new_hrs-24;
if(new_hrs < 10)
new_hrs = '0'+new_hrs;
var second_time = new_hrs+':'+arr[1];
$('#new_two').val(second_time);
});
});
</script>
</head>
<body>
Text1<input type="text" id="new_one"><br/>
Text2<input type="text" id="new_two">
</body>
</html>
Here is the working fiddle : Working Fiddle
$('#one').on('change',function (e) {
var first_time = $(this).val();
var arr = first_time.split(':');
var hrs = arr[0];
var new_hrs = parseInt(hrs)+6;
if(new_hrs>24)
new_hrs = new_hrs-24;
if(new_hrs < 10)
new_hrs = '0'+new_hrs;
var second_time = new_hrs+':'+arr[1];
$('#two').val(second_time);
});
It is pretty basic just split the input string of first box on ':' using .split(':') and increment hours accordingly and put the computed value to second box
$(document).ready(function()
{
$("#firstTime").keypress(function(){
var firsttime = $(this).val();
var gettime = $.trim(firsttime).split(":");
var updatetime = parseInt(gettime [0])+6;
if(updatetime > 24)
{
updatetime = updatetime-24;
}
if(updatetime < 10)
{
updatetime = "0"+updatetime;
}
$("#secondtime").val(updatetime+":"+gettime [1]);
});
});
Where your HTML will be:
<input type="text" id="firsttime"><!-- first time -->
<input type="text" id="secondtime"><!-- second time -->
You can also leverage DateJS to simplify the calculation as listed below. Here's an example in JS Fiddle. Note, there's no validation checks and number of hours to add is hard-coded at 6.
<!DOCTYPE html>
<html>
<head>
<title>Time Sample</title>
</head>
<body>
Start Time: <input id="startTime" type="text" /><br />
End Time: <input id="endTime" type="text" />
<script src="Scripts/jquery-1.8.2.js"></script>
<script src="Scripts/date.js"></script>
<script>
$(function () {
$("#startTime").change(function () {
var endTime = Date.parse(this.value).add(6).hours();
$("#endTime").val(endTime.toString("H:mm"));
});
});
</script>
</body>
</html>