I'm using MVC2 and have included the Jquery DateTime picker.
For some reason it is not using the default format settings when the pages loads.
The model is passing in a Date and I have set the format to 'dd/mm/yyyy' as I do not want the time to be displayed. The html.editorfor that the datepicker is attached to, shows in the standard 'mm/dd/yyyy hh:mm:ss' format, consequently the validation kicks in with "invalid Date" if the model value if say '15th October 2010', because the standard format complains that there is no "15th" month.
Code from the DatePicker is...
<%= Html.TextBox("", (Model.HasValue ? Model.Value.Date.ToString("dd/mm/yyyy") :
DateTime.Today.ToString("dd/mm/yyyy") ), new { #class = "date" }) %>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#datepicker").datepicker(
{
dateFormat: 'dd/mm/yy',
defaultDate: new Date(),
minDate: new Date()
});
});
</script>
Code calling Datepicker...
<div>
<%=Html.LabelFor(Model => Model.StartDate)%>
<%=Html.EditorFor(Model => Model.StartDate, new { #class = "date" }) %>
<%=Html.ValidationMessageFor(Model => Model.StartDate, "*")%>
</div>
Any ideas?
It seems the problem is actually with the HTML.TextBox rather than the actual JQuery...
This line seems to be the problem,
<%= Html.TextBox("", (Model.HasValue ? Model.Value.Date.ToString("dd/MMM/yyyy") :
DateTime.Today.ToString("dd/MMM/yyyy")), new { #class = "date" })%>
I have broken down the line as follows to check the different elements are working correctly, and they are...
<div><%= Model.HasValue %></div>
<div><%= Model.Value.Date.ToString( "dd/MM/yyyy" ) %></div>
<div><%= DateTime.Today.ToString("dd/MM/yyyy")%></div>
So, simply - this line in a template causes the date formatting to be ignored... any suggestions?
<div><%= Html.TextBox("", Model.Value.Date.ToString("dd/MM/yyyy"))%></div>
Are you setting the ID of the textBox correctly, I can see you have a class "date" but not the id.
you may also need the localization files for the datepicker available at Google
I still can't see in your javascript where the selector:
$("#datepicker")
is associated to your textbox. Shouldn't the selector be
$('.date')
Maybe I'm missing something.
Related
I am trying to get and modify a date value, I get the date value from mongoose, I correctly get the value, and I can modify it correctly, but moongoose give me the date in this format :
YYYY-MM-DDT00:00:00.000Z,
So I want to change the display value with an Italian format, like: DD/MM/YYYY.
I have try with this:
<template>
<div class="col">
<span> Date </span>
<input
:value="birth" v-on:input="birth = $event.target.value" type="date" />
</div>
</template>
<script>
import DataService from '#/services/DataService'
import ClickToEdit from '#/components/ClickToEdit'
import moment from 'moment'
export default {
name: 'Options',
data: function() {
return {
birth: '',
}
},
methods: {
async getAllInfo() {
var userInfo = await DataService.getInfoFromSomeWhere({
})
this.birth = this.frontEndDateFormat(userInfo.data.user[0].birth)
},
frontEndDateFormat: function(date) {
return moment(date, 'YYYY-MM-DDT00:00:00.000Z').format('DD/MM/YYYY')
}
},
mounted() {
this.getAllInfo()
}
}
</script>
The date was correctly changed, but the vue page didn't display the date value, and I think is because the default input value display the date in this way :
gg/mm/aaaa
I have already try to change the frontEndDateFormat method with gg/mm/aaaa instead of DD/MM/YYYY, but If I do this I have a strange value in input, like gg/00/amamamama ( I think the problem is related to moment).
So I tried to use :
<input :value="birth" v-on:input="birth = $event.target.value" type="date" v-model="date" />
But If I get an error:
:value="birth" conflicts with v-model on the same element because the
latter already expands to a value binding internally
What am I doing wrong? Thank you
I am new to react and trying to get the actual date and time but I can't figure out how to do so :(
Could someone help me please !
I try to get the date in the initial state and actualise it every second. When I run it, I get a white screen.
import React from 'react';
import './Menubar.css';
import Time from 'react-time';
const Menubar = React.createClass({
getInitialState() {
return {
now: new Date().now(),
};
},
getRealTime: function() {
this.setState(
{
now: new Date().now(),
})
},
/**
* Render the Menubar component
* #return {Component} the App Component rendered
*/
render() {
setInterval(this.getRealTime(), 1000);
return (
<div className="Menubar">
<ul className="Menubar-menu">
<div className="">
<li className="Menubar-name">login name</li>
<li className="Menubar-date"><Time value={this.state.now} format="DD/MM/YYYY" /></li>
<li className="Menubar-time"><Time value={this.state.now} format="HH:mm:ss" /></li>
</div>
</ul>
</div>
);
}
});
export default Menubar;
Two things:
new Date().now() is not a function, new Date() returns the current date and time, so no need to add it.
You try to set the state inside the render function (calling getRealTime every single render, which causes a re-render). As I understand, you want to update the time every second. You could set that up in componentDidMount.
Here's your Menubar component with those things fixed. I also clear the interval when the component unmounts:
const Menubar = React.createClass({
getInitialState() {
return {
now: new Date(),
};
this.interval = null;
},
componentDidMount: function() {
const self = this;
self.interval = setInterval(function() {
self.setState({
now: new Date(),
});
}, 1000);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
render() {
return (
<div className="Menubar">
<ul className="Menubar-menu">
<div className="">
<li className="Menubar-name">login name</li>
<li className="Menubar-date"><Time value={this.state.now} format="DD/MM/YYYY" /></li>
<li className="Menubar-time"><Time value={this.state.now} format="HH:mm:ss" /></li>
</div>
</ul>
</div>
);
}
});
To just get the current date you can use
var dateVariable = new Date()
dateVariable.getDate()
OR if you want the current Date & Time in full form then,
var dateVariable = Date().toLocaleString()
You can find a comprehensive list of methods available on:
https://hdtuto.com/article/react-js-get-current-date-and-time-example
The above link saved a lot of my time. Hope it works. Happy hacking!
I just want to add to IronmanX46's answer, but it won't let me comment.
I wanted to point out that you can do the exact same thing as
var dateVariable = new Date()
dateVariable.getDate()
var dateVariable = Date().toLocaleString()
by simply doing
var dateVariable = Date()
As per the documentation:
Date()
When called as a function, returns a string representation of the
current date and time. All arguments are ignored. The result is the
same as executing new Date().toString().
There are lots of good websites out there that will give you examples of how to do things, but I find it saves time to just go read the documentation, which usually includes examples. I'll then go check out other examples if I can't understand the documentation.
Date Documentation Link
I'm using Angular2 and a forked version of Semantic-UI (that includes calendar module). I'm using calendar and dropdown features:
constructor() {
setTimeout(() => {
jQuery('.ui.dropdown').dropdown();
jQuery('.ui.calendar').calendar({ type: 'date' });
}, 1000);)
}
Here is my Plunker.
As you can see I can't get input from calendar selection.
I can't understand what could be the glitch. Can you figure out what could be the problem?
For some unknown reason [(ngModel)] is not getting updated.
But if its a matter of getting date only, you could use #templateVariable as shown here.
Working DEMO : https://plnkr.co/edit/X8Gjwzd62DvYN1S8jrFv?p=preview
Using #TemplateVariable
<input #date type="text" placeholder="Date">
<button (click)="test(date.value)">test</button>
test(date):void {
console.log(date);
console.log(this.name);
}
Using #ViewChild
#ViewChild('date') date:ElementRef;
test(date):void {
console.log(this.date.nativeElement.value);
console.log(date);
console.log(this.name);
}
I'm trying to create a dual date object in Angular2 and I have no idea how it can be accomplished.
What I mean by a dual date object is basically creating a single instance of a date picker using Kendo UI (screenshot of a date picker from Kendo UI). Once it's clicked, two instances of the date object appears. The first is for 'Start date' and the second is for 'End Date'. The date object uses Kendo UI.
Basically it's for users to select a date range. I would really appreciate any help on this. Thank you.
The Kendo UI DatePicker can work with one date only. For selecting a date range, use two widget instances.
http://demos.telerik.com/kendo-ui/datepicker/rangeselection
It is theoretically possible to use a Kendo UI Popup with two Calendar instances inside, and store the two date values somewhere, according to your preferences.
<style>
#popup > div {display: inline-block; }
#textbox { width: 300px; }
</style>
<p>Focus the textbox:</p>
<input id="textbox" class="k-textbox" />
<div id="popup">
<div id="calendar1"></div>
<div id="calendar2"></div>
</div>
<script>
var textbox = $("#textbox");
$("#popup").kendoPopup({
anchor: textbox
});
$("#calendar1").kendoCalendar({
change: updateTextBox
});
$("#calendar2").kendoCalendar({
change: updateTextBox
});
textbox.focus(function(){
$("#popup").data("kendoPopup").open();
});
function updateTextBox() {
textbox.val("use the Calendars' value method here");
}
</script>
How to disable previous dates while using in ajaxToolkit CalendarExtender
One Option is to use a rangevalidator on the textbox the calenderextender is bound to. Ie if you have the TargetID of the calendar extender set to tb1 add a rangeValidator to flag when the contents of tb1 is before today.
Another option is using javascript and here is a good example:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=149 TIP 6.
Here is my full solution to the calendar date restriction problem: What I like about this solution is that you set the MinimumValue and MaximumValue of a RangeValidator and you do not have to modify any javascript. I never found a full solution that did not require recompiling the AjaxControlToolkit.dll. Thanks to http://www.karpach.com/ajaxtoolkit-calendar-extender-tweaks.htm for giving me the idea of how to override key methods in the calendar.js file without having to recompile the AjaxControlToolkit.dll. Also, I got "AjaxControlToolkit is undefined" javascript errors, so I changed those to Sys.Extended.UI. and it works for me when using the 4.0 version of the toolkit.
<%--//ADD THIS NEW STYLE TO STYLESHEET TO GRAY OUT DATES THAT AREN'T SELECTABLE--%>
<style type="text/css">
.ajax__calendar_inactive {color:#dddddd;}
</style>
Either in Page_Load or Init or wherever, set the min and max values for your range validator:
<script runat="server">
protected override void OnLoad(EventArgs e)
{
//set the validator min and max values
this.valDateMustBeWithinMinMaxRange.MinimumValue = DateTime.Today.Date.ToShortDateString();
this.valDateMustBeWithinMinMaxRange.MaximumValue = DateTime.MaxValue.Date.ToShortDateString();
base.OnLoad(e);
}
</script>
Add this javascript somewhere in your page:
<script type="text/javascript">
<%--// ADD DATE RANGE FEATURE JAVASCRIPT TO OVERRIDE CALENDAR.JS--%>
var minDate = new Date('<%= valDateMustBeWithinMinMaxRange.MinimumValue %>');
var maxDate = new Date('<%= valDateMustBeWithinMinMaxRange.MaximumValue %>');
Sys.Extended.UI.CalendarBehavior.prototype._button_onblur_original = Sys.Extended.UI.CalendarBehavior.prototype._button_onblur;
//override the blur event so calendar doesn't close
Sys.Extended.UI.CalendarBehavior.prototype._button_onblur = function (e) {
if (!this._selectedDateChanging) {
this._button_onblur_original(e);
}
}
Sys.Extended.UI.CalendarBehavior.prototype._cell_onclick_original = Sys.Extended.UI.CalendarBehavior.prototype._cell_onclick;
//override the click event
Sys.Extended.UI.CalendarBehavior.prototype._cell_onclick = function (e) {
var selectedDate = e.target.date;
if (selectedDate < minDate || selectedDate > maxDate ) {
//alert('Do nothing. You can\'t choose that date.');
this._selectedDateChanging = false;
return;
}
this._cell_onclick_original(e);
}
Sys.Extended.UI.CalendarBehavior.prototype._getCssClass_original = Sys.Extended.UI.CalendarBehavior.prototype._getCssClass;
Sys.Extended.UI.CalendarBehavior.prototype._getCssClass = function (date, part) {
var selectedDate = date;
if (selectedDate < minDate || selectedDate > maxDate ) {
return "ajax__calendar_inactive";
}
this._getCssClass_original(date, part);
}
</script>
Add this text box to your asp.net page with CalendarExtenter and RangeValidator:
<asp:TextBox ID="textBoxDate" runat="server" />
<ajaxToolkit:CalendarExtender ID="calendarExtender" runat="server" TargetControlID="textBoxDate" />
<asp:RangeValidator ID="valDateMustBeWithinMinMaxRange" runat="server" ControlToValidate="textBoxDate"
ErrorMessage="The date you chose is not in accepted range" Type="Date" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
Using the Ajax toolkit Calendar Extender in the html markup:
<asp:TextBox ID="txtDate" runat="server" CssClass="contentfield" Height="16px" MaxLength="12" width="80px" Wrap="False"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender3" runat="server" Enabled="true" StartDate="<%# DateTime.Now %>" EndDate="<%# DateTime.Now.AddDays(1) %>" Format="dd MMM yyyy" PopupButtonID="imgDatePicker" TargetControlID="txtDate">
</asp:CalendarExtender>
<asp:ImageButton ID="imgDatePicker" runat="Server" AlternateText="Click to show calendar" Height="16px" ImageAlign="Middle" ImageUrl="~/images/Calendar_scheduleHS.png" Width="16px" />
Above you will see that the Calendar only allows one to choose between today or tomorrow by setting
StartDate="<%# DateTime.Now %>"
and
EndDate="<%# DateTime.Now.AddDays(1) %>"
This can also be done in the backend using CalendarExtender1.StartDate = DateTime.Now; or CalendarExtender1.EndDate = DateTime.Now.AddDays(1);
Just add an attribute StartDate="<%# DateTime.Now %>" in you ajaxtoolkit calendarextender control
Following link might help you:
Disable dates in CalendarExtender