Html5 type date - need full date value in database - sql

it is my html code
<div class="required" id="join_form">
<label for="DOB">DateOfBirth:</label>
<input type="date" name="date" id="date" required pattern="(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d" aria-required="true" aria-describedby="age-format" max="2004-12-31" min="1940-12-31" />
<span id="age-format" class="help" align="center">Format: mm/dd/yyyy, mm-dd-yyyy, mm.dd.yyyy, mm dd yyyy</span>
</div>
javascript to validate this type=date in other browsers
var mydate = document.getElementById('date'),
mydateError = document.getElementById('age-format');
mydate.addEventListener('input', function() {
if (!mydate.value.match(/\d{4}-\d{1,2}-\d{1,2}/)) {
mydateError.innerHTML = 'Please specify a valid date in the form 1940-2004 ';
mydateError.style.display = 'inline-block;font-size:6pt;text-align:center;';
} else {
var value = new Date(date.value),
min = new Date(date.min),
max = new Date(date.max);
if (value < min || value > max) {
mydateError.innerHTML = 'Date has to be between ' + min.toDateString() + ' and ' + max.toDateString();
mydateError.style.display = 'inline-block';
} else {
mydateError.style.display = 'none';
}
}
});
php validation and insert for date
$DOB=mysql_real_escape_string($_POST['date']);
$sql="INSERT INTO register(DOB) VALUES("$DOB");
i want to get whole date of birth like mm/dd/year but in my database i am only getting year like 1970 or 1987 like that....i cant figure out where i got wrong

PHP mysql insert date format
This Link did help me I used this to validate and insert type="date" in database
$timestamp = strtotime($DOB);
$date = date('d-m-y', $timestamp);
$sql="INSERT INTO register(DOB) VALUES(FROM_UNIXTIME($timestamp))";
and my other Mistake was to set DOB as int in database
Data type required in a mysql for a date containing day-month-year
it should be DATE or DATETYPE
#Tonywilk Thankx :D

Related

Show date from database on Picker materialize

I have the following code, when I click on the Picker I want to see the date 01/01/2018 selected in the calendar.
I need the calendar to select the date that contains the value of the imput.
$var_date = '01/01/2018';
<input type="text" name="date" name="date" class="datepicker" value="<?php echo $var_date; ?>">
<label for="first_name">Date</label>
This can be done with the help of instance.setDate(new Date()).
<input type="text" class="datepicker">
<script>
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelector('.datepicker');
var instance = M.Datepicker.init(elems);
// instance.open(); This will open your datepicker on its own when page is loaded completely
instance.setDate(new Date(2018, 2, 8));
});
</script>
Note- new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
The argument monthIndex is 0-based. This means that January = 0 and December = 11
MDN - Date
Materialize - Pickers

Date comparision on cshtml view

I am using the below code to compare 2 dates on cshtml view with knockout binding.
data-bind="visible: (new Date(appointmentDate) - new Date() < 0) && isStart()"
It is working fine but that is including time as well while comparing. I don't want to include time in comparision only date.
I quick search on google pointed me to Formatting Date in Knockout Template this will allow us to get the date and compare it. Looking like
data-bind="visible: (
moment(new Date(appointmentDate)).format('MM/DD/YYYY') -
moment(new Date()) < 0) && isStart()"
I didn't try just let me know if works
Also momento allows you to calculate difference of dates
var dateB = moment('2014-11-11');
var dateC = moment('2014-10-11');
console.log('Difference is ', dateB.diff(dateC), 'milliseconds');
console.log('Difference is ', dateB.diff(dateC, 'days'), 'days');
console.log('Difference is ', dateB.diff(dateC, 'months'), 'months');
So basically we would do
data-bind="visible: (
moment(new Date(appointmentDate)).format('MM/DD/YYYY').diff(new Date().format('MM/DD/YYYY'),'days') < 0) && isStart()"

VueJS: How to bind a datetime?

I receive from a WebAPI a JSON object that has this property:
"BirthDate": "2018-02-14T15:24:17.8177428-03:00",
the HTML:
<input type="date" v-model="BirthDate" />
I bind that object using VueJS, but
VueJS give this message in the console:
The specified value "2018-02-14T15:24:17.8177428-03:00" does not conform to the required format, "yyyy-MM-dd".
On this case the only relevant part is 2018-02-14, I can discard the other information.
I tried to create a Two Way filter to convert that Date Time to the required format but did not have success. See VueJS two way filter
How can I convert and bind that Date/Time format to the required Date Format of the HTML date input ?
Considering myDate is your property, you can use:
<input type="date" :value="myDate && myDate.toISOString().split('T')[0]"
#input="myDate = $event.target.valueAsDate">
Since v-model is only syntactic sugar to :value and #input, you can use them instead. In this case, we used and changed them a little (to format the String that is the output of the date input to a Date object and vice-versa).
Check demo and caveats below.
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
myDate: new Date('2011-04-11T10:20:30Z')
},
methods: {
setMyDateToToday() {
this.myDate = new Date();
},
addADayToMyDate() {
if (this.myDate) // as myDate can be null
// you have to set the this.myDate again, so vue can detect it changed
// this is not a caveat of this specific solution, but of any binding of dates
this.myDate = new Date(this.myDate.setDate(this.myDate.getDate() + 1));
},
}
});
// Notes:
// We use `myDate && myDate.toISOString().split('T')[0]` instead
// of just `myDate.toISOString().split('T')[0]` because `myDate` can be null.
// the date to string conversion myDate.toISOString().split('T')[0] may
// have timezone caveats. See: https://stackoverflow.com/a/29774197/1850609
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p>{{ message }}</p>
<input type="date" :value="myDate && myDate.toISOString().split('T')[0]"
#input="myDate = $event.target.valueAsDate">
<p>
<code>
myDate: {{ myDate }}</code>
</p>
<button #click="setMyDateToToday">Set date one to today</button>
<button #click="addADayToMyDate">Add a day to my date</button>
</div>
i think this not related to vueJs , the input type="date" expected a date in YYYY-MM-DD format, or empty
see here : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date,
it would be better if you split date object as date and time field
Correction to #acdcjunior in that this shouldn't be off by one day
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
myDate: new Date('2011-04-11T10:20:30Z')
},
methods: {
setMyDateToToday() {
this.myDate = new Date();
},
addADayToMyDate() {
if (this.myDate) // as myDate can be null
// you have to set the this.myDate again, so vue can detect it changed
// this is not a caveat of this specific solution, but of any binding of dates
this.myDate = new Date(this.myDate.setDate(this.myDate.getDate() + 1));
},
getDateClean(currDate) {
// need to convert to UTC to get working input filter
console.log(currDate);
let month = currDate.getUTCMonth() + 1;
if (month < 10) month = "0" + month;
let day = currDate.getUTCDate();
if (day < 10) day = "0" + day;
const dateStr =
currDate.getUTCFullYear() + "-" + month + "-" + day + "T00:00:00";
console.log(dateStr);
const d = new Date(dateStr);
console.log(d);
return d;
}
}
});
// Notes:
// We use `myDate && myDate.toISOString().split('T')[0]` instead
// of just `myDate.toISOString().split('T')[0]` because `myDate` can be null.
// the date to string conversion myDate.toISOString().split('T')[0] may
// have timezone caveats. See: https://stackoverflow.com/a/29774197/1850609
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p>{{ message }}</p>
<input type="date" :value="myDate && myDate.toISOString().split('T')[0]"
#input="myDate = getDateClean($event.target.valueAsDate)">
<p>
<code>
myDate: {{ myDate }}</code>
</p>
<button #click="setMyDateToToday">Set date one to today</button>
<button #click="addADayToMyDate">Add a day to my date</button>
</div>

SQL how to select data in terms of weeks

Is it in any way possible to select data from the database in spans of weeks?
I use cshtml (not MVC) and webmatrix if that makes any difference.
var dbQueryAllVariants = "SELECT * FROM Test WHERE exercise = " + exercise + " AND date >= '" + fromDate + "' AND date <= '" + toDate + "'";
So right now I'm using this, I put in a start date (ex. 2016-11-01) and end date (ex. 2016-11-30) (yyyy-mm-dd cuz north europe). This displays all the data in the database between those dates but since all rows in the database only have a day as date, the result to be viewed would be in day form, I'd like if it can do weeks, in this case, from first to last november as an example would be aprox 4 weeks, is this possible? Also, the data in the database is int values so I would like to be able to add those up to display a total of the week that gets displayed if that makes sense.
For example.
column 1 column 2 column 3
5 . . . . 6 . . 2016-11-13
8 . . . . 10 . . 2016-11-15
6 . . . . 3 . . 2016-11-17
So as of right now it would display 3 days with a sum of 11 for day 1, 18 for day 2 and 9 for day 3, but while displayed in terms of weeks it would be 11+18+9=38, as for an example. This might not even be possible to begin with but I'd like to know how to do this if possible!
If this isn't a possible solution, is there a way to like select all the data in day form, put it in a array or whatever, and from there send it grouped as a weekly total based on the weeks of the year (ex. november contains week 44-48) something like that? What I'm trying to say is that if the end result is what I want, it doesn't matter how its done.
#{
//Calls for my website layout.
Layout = "~/_SiteLayout.cshtml";
//Browser title of the specific page.
Page.Title = "TEST";
//Opens database.
var db = Database.Open("SmallBakery");
//Variables.
var exercise = Request.Form["Exercise"];
var fromDate = Request.Form["fromDate"];
var toDate = Request.Form["toDate"];
var exerVariName = "";
var exerVariNameS = "";
var exerVariNameB = "";
var exerVariNameD = "";
//Defaults to show data between these
//dates if user dont choose any dates.
var noStartDate = "1970-01/01";
var noEndDate = "2099-12/31";
//If user does not choose eiter/any start/end date
//this will end up showing all results possible.
if (fromDate == "") {
fromDate = noStartDate;
}
if (toDate == "") {
toDate = noEndDate;
}
//Takes exerVariName from different dropdowns
//depending on which exercise is selected due to
//the fact that only one dropdown is visible at any time.
if (exercise == "1") {
exerVariName = Request.Form["exerVariNameS"];
} else if (exercise == "2") {
exerVariName = Request.Form["exerVariNameB"];
} else {
exerVariName = Request.Form["exerVariNameD"];
}
//Gets exercise variants to the dropdown menu.
var getSVariName = "SELECT * FROM exerciseVariants WHERE exerVariNameID = 1 ORDER BY exerVariName";
var getBVariName = "SELECT * FROM exerciseVariants WHERE exerVariNameID = 2 ORDER BY exerVariName";
var getDVariName = "SELECT * FROM exerciseVariants WHERE exerVariNameID = 3 ORDER BY exerVariName";
var getData = "SELECT * FROM Test";
//Gets the date.
var getDate = "SELECT date FROM Test";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<!-- Form for posting. -->
<form method="post" action="">
<!-- Radio buttons to select which data to show. -->
<div>
<label>Squat</label>
<input type="radio" name="Exercise" id="hej1" value="1" />
</div>
<div>
<label>Benchpress</label>
<input type="radio" name="Exercise" id="hej2" value="2" />
</div>
<div>
<label>Deadlift</label>
<input type="radio" name="Exercise" id="hej3" value="3" />
</div>
<div>
<!-- Dropdown menu with squat-variant-names. -->
<select id="exerVariNameS" name="exerVariNameS">
<option value="all">All</option>
<option value="Comp">Competition</option>
#foreach (var get in db.Query(getSVariName)) {
//Gets the exercise variation names from
//the database and puts them in a dropdown.
<option value="#get.exerVariName">#get.exerVariName</option>
}
</select>
<!-- Dropdown menu with bench-variant-names. -->
<select id="exerVariNameB" name="exerVariNameB">
<option value="all">All</option>
<option value="Comp">Competition</option>
#foreach (var get in db.Query(getBVariName)) {
//Gets the exercise variation names from
//the database and puts them in a dropdown.
<option value="#get.exerVariName">#get.exerVariName</option>
}
</select>
<!-- Dropdown menu with deadlift-variant-names. -->
<select id="exerVariNameD" name="exerVariNameD">
<option value="all">All</option>
<option value="Comp">Competition</option>
#foreach (var get in db.Query(getDVariName)) {
//Gets the exercise variation names from
//the database and puts them in a dropdown.
<option value="#get.exerVariName">#get.exerVariName</option>
}
</select>
</div>
<div>
<!-- Date calendar. -->
<input placeholder="From date..." type="text" class="datepicker" name="fromDate" value="#fromDate">
</div>
<div>
<!-- Date calendar. -->
<input placeholder="To date..." type="text" class="datepicker" name="toDate" value="#toDate">
</div>
<!-- The submit button. -->
<input type="submit" value="Show" class="submit" />
</form>
<!-- Displays database value on submit click based on choosen radiobutton from form-post above. -->
#if (IsPost) {
//When I select ALL in the dropdown it runs
//this line because there is no filter for 'exerVariName'.
// var dbQueryAllVariants = "SELECT * FROM Test WHERE exercise = " + exercise + " AND date >= '" + fromDate + "' AND date <= '" + toDate + "'";
//When I select a specific exercise variation.
var dbQuerySingleVariant = "SELECT * FROM Test WHERE exercise = " + exercise + " AND exerVariName = '" + exerVariName + "' AND date >= '" + fromDate + "' AND date <= '" + toDate + "'";
//This is what the problem is....
var dbQueryAllVariants = "SELECT DATEPART(week, date) AS weekNumber, sum(kg)+sum(sett) AS grandTotalPerWeek FROM Test WHERE Exercise = " + exercise + " AND DATEPART(week, date) BETWEEN DATEPART(week, " + fromDate + ") AND DATEPART(week, " + toDate + ") GROUP BY DATEPART(week, date)";
var dbQuery = "";
//If dropdown = select all, it does, else, it show the one I pick.
if (exerVariName == "all") {
dbQuery = dbQueryAllVariants;
} else {
dbQuery = dbQuerySingleVariant;
}
//Foreach to write out all the data from db.
var sumTotalWeight = 0;
foreach (var get in db.Query(dbQuery)) {
<a>Weight: </a>
<a>#get.Kg kg</a>
<a> Sets: </a>
<a>#get.Sett</a>
<a> Reps: </a>
<a>#get.Rep</a>
<a> Total reps: </a>#(get.Sett * get.Rep)
<a> #get.date</a>
var totalWeight = #get.Kg * #get.Sett * #get.Rep;
sumTotalWeight += totalWeight;
<a> #totalWeight</a>
<br>
}
#sumTotalWeight
}
</body>
From your comments one may conclude you are using the MSSQL Server Compact Edition.
If that's correct then you could use the DATEPART function to extract the week of the year for each date, and then group by week and sum all results for each.
Something like this:
SELECT
sum(column1)+sum(column2) AS grandTotalPerWeek
FROM Test
WHERE Exercise = {Exercise}
AND DATEPART(week, date) = {weekNumber}
Where {Exercise} and {weekNumber} are the variables to be substituted.
Or like this, if you need to request multiple weeks at once:
SELECT
DATEPART(week, date) AS weekNumber,
sum(column1)+sum(column2) AS grandTotalPerWeek
FROM Test
WHERE Exercise = {Exercise}
AND DATEPART(week, date) IN ({listOfWeekNumbers})
GROUP BY DATEPART(week, date)
Where {Exercise} and {listOfWeekNumbers} are the variables to be substituted.
In either case, when we talk about week numbers we talk about integer values. 1 means the first week of the year, 2 the second week, ...
Example: Get the values for January
SELECT
DATEPART(week, date) AS weekNumber,
sum(kg)+sum(sett) AS grandTotalPerWeek
FROM Test
WHERE Exercise = 1
AND DATEPART(week, date) IN (1,2,3,4)
GROUP BY DATEPART(week, date)
So, to use this SQL you need to translate dates into week numbers. If you only have dateFrom and dateTo then you can try something like this:
SELECT
DATEPART(week, date) AS weekNumber,
sum(kg)+sum(sett) AS grandTotalPerWeek
FROM Test
WHERE Exercise = 1
AND DATEPART(week, date) BETWEEN DATEPART(week, {dateFrom}) AND DATEPART(week, {dateTo})
GROUP BY DATEPART(week, date)
DATEPART documentation on MSDN.

Bootstrap DatePicker Splitting Date

I'm in the process of updating an old booking systems views and I am presently stuck on a solution for updating the calendar widget. As the site is responsive I have opted for the bootstrap datepicker supplied by eternicode https://github.com/eternicode/bootstrap-datepicker.
OK here the issue. I have an old Datepicker that splits the checkin & checkout dates into 3 parts and then formats the date for PHP (n = Month no leading zero)) (j = Day no leading zero) & (Y = Year 4 digit numeric).
// Initiate Params
$checkInDate = mktime(0,0,0,date("n"),date("j") + 1,date("Y"));
$checkOutDate = mktime(0,0,0,date("n"),date("j") + 3,date("Y"));
//CheckInDate
if (!isset($daysI)){
$daysI = date("j",$checkInDate);
}
if (!isset($monthsI)){
$monthsI = date("n",$checkInDate);
}
if (!isset($yearI)){
$yearI = date("Y",$checkInDate);
}
//CheckOutDate
if (!isset($daysS)){
$daysS = date("j",$checkOutDate);
}
if (!isset($monthsS)){
$monthsS = date("n",$checkOutDate);
}
if (!isset($yearS)){
$yearS = date("Y",$checkOutDate);
}
The input boxes markup is as below.
<input type='text' id='fulldate' name='fulldate'>
<label>Enter Day of Arrival (in the format DD) </label>
<input type="text" name="daysI" id="daysI" size="6" maxlength="6" />
<label>Enter Month of Arrival (in the format MM) </label>
<input type="text" name="monthsI" id="monthsI" size="6" maxlength="6" />
<label>Enter Year of Arrival (in the format YYYY) </label>
<input type="text" name="yearI" id="yearI" size="6" maxlength="6" />
Here's where I'm having the problem. The following function works with jQuery UI:
$('#fulldate').datepicker({
showAnim: 'fadeIn',
dateFormat: 'd/m/yy',
onSelect: function(dateText, inst) {
var pieces = dateText.split('/');
$('#daysI').val(pieces[0]);
$('#daysI').val(pieces[1]);
$('#daysI').val(pieces[2]);
}
});
However I cannot get a similar solution to work with the bootstrap-datepicker which I am using as a replacement for jQuery UI ie:
$('#fulldate').datepicker({
format: "d/m/yyyy",
todayBtn: "linked",
todayHighlight: true
onSelect: function(dateText, inst) {
var pieces = dateText.split('/');
$('#daysI').val(pieces[0]);
$('#monthsI').val(pieces[1]);
$('#yearI').val(pieces[2]);
}
});
Thank in advance for any solution..
The documentation gives an example of how to capture the date changed event: bootstrap-datepicker Docs - Change Date Event
Something like this should be in the right direction (untested):
$('#fulldate').datepicker()
.on('changeDate', function(ev){
var newDate = new Date(ev.date);
$('#daysI').val(newDate.getDate());
$('#monthsI').val(newDate.getMonth());
$('#yearI').val(newDate.getFullYear());
});