Getting the correct format of the datepicker - javascript

I have a column inside of my datebase that stores a date that user pick when they offer a job. It's currently formed in this way: "Fri Feb 15 2019".
I want to be able to compare it to the current date which is formed as: "2019-01-27"
I'm guessing that the best way to do this would be to transform the datepicker format to the date one, and then compare them. This is the code that I have for the date picker currently when someone registeres.
<div class="form-group">
<label for="location" class="control-label">DATE</label>
<input type="text" id="datepicker" class="form-control" placeholder="Pick a
date" name="datepicker">
</div>
<script>
var picker = new Pikaday({ field: document.getElementById('datepicker') });
</script>

Open the example in full page :
Use new Date and then you can extract the day the month and the year
and to compare with another date, you can just new Date("2006-05-1").getMonth() === new Date("2006-05-2").getMonth() && ...
var picker = new Pikaday({
field: document.getElementById('datepicker')
});
const dateInput = document.getElementById('datepicker');
function handleChange() {
const date = new Date(dateInput.value),
formattedDate = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`;
console.log(formattedDate)
}
dateInput.addEventListener("change", handleChange);
<script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css">
<input type="text" id="datepicker">

I would suggest using the javascript plugin called Momentjs. It allows for easy formatting of dates, without the base javascript hassle.
Add this to your HTML, near the bottom of your page, but before your script tags:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Then to format your datepicker value, inside your script, use:
var myDate = moment(picker.value).format('YYYY-MM-DD');
Here is the Momentjs documentation:
Momentjs Docs

Related

Bootstrap Datepicker With Daterange Not Saving Value as the Specified Format

I have a booking form that requires two dates, so I'm using the built in option that Bootstrap datepicker has (it consists on calling the datepicker function on the father element that contains the inputs), to show the daterange selected, this is my HTML:
<div class="grupo vip-fechas input-daterange">
<div class="barra verde"> <span>¿Cuándo llegas?</span></div>
<input type="text" class="input calendario" id="entrada_input" name="entrada_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_inicio" name="fecha_inicio">
<div class="barra verde"> <span>¿Cuándo te vas?</span></div>
<input type="text" class="input calendario" id="salida_input" name="salida_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_fin" name="fecha_fin">
</div>
This is my Javascript code:
$(document).ready(function(){
iniciarFechas();
});
function iniciarFechas(){
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var date_hidden;
$('.vip-fechas.input-daterange').datepicker({
weekStart: 1,
maxViewMode: 1,
language: "es",
startDate: today,
disableTouchKeyboard: true,
format: {
toDisplay: function(date, format, language) {
var fecha = moment(date).add(1,"day");
date_hidden = fecha;
return fecha.format("dddd DD [de] MMMM, YYYY");
},
toValue: function(date, format, language) {
var fecha = moment(date).add(1,"day");
return moment(fecha).format("DD/MM/YY");
//return moment(date, ["DD.MM.YYYY", "DDMMYYYY"]).toDate();
}
},
}).on("changeDate", function(e){
var fecha_formateada = moment(date_hidden).format("DD/MM/YY");
$(this).next().val(fecha_formateada);
});
}
The daterange works correctly but I want to store the formatted date inside the hidden inputs, as you can see, the format that I want is this: ...format("DD/MM/YY"); but what I get is the display format: format("dddd DD [de] MMMM, YYYY"), also I noticed that $(this) value within this line: $(this).next().val(fecha_formateada); refers to the container div, and not the input that has changed value, so how can I save the date as I want inside the hidden inputs?
I'm not sure what your problem is but by looking at your code I can only guess that you might be in the middle of a race condition.
You're setting the date_hidden variable in Datepicker.toDisplay and then reading from it in the changeDate custom event.
Put a debugger or a console log in both callbacks to make sure you're not in the middle of a race condition.
As for setting the formatted value in the input fields, well I can see in your HTML code that you have selectors that you can use, like the hidden field's ID for example.
Another thing I'd suggest is, instead of setting and reading the date_hidden field in those different callbacks, just call $('#elementID').datepicker('getDate') in the changeDate event handler and do all the transformations you need there, then extract that code and put it in a separate function.

How to set selected date on Jquery Calendar Plugin

So I am using the calendar app on a page that has a set date. I have it so when you click on the calendar, whatever is in the input that has the date, gets changed to the date you clicked on.
When you load into the page I want whatever date that is in the input to be what the calendar is set to. Thanks.
LINK TO PLUGIN - https://www.jqueryscript.net/time-clock/Simple-jQuery-Calendar-Date-Picker-Plugin-DCalendar.html
var pageDate = "4/04/2018";
<input class="date">
$('.date').val(pageDate);
// Make above date the selected date
// Code below is for setting input to date you select. Currently works.
$('.box').dcalendarpicker({
format: 'mm-dd-yyyy'
}).on('datechanged', function(e) {
console.log('Date change');
var d = e.date;
selectedDate = moment(d, 'MM-DD-YYYY');
var theDate = selectedDate._i;
$('.date').val(theDate);
var weekdayLongform = selectedDate.format("dddd, MMMM");
var dateLongform = selectedDate.format(" D");
var yearLongform = selectedDate.format(" YYYY");
});
Just set the date as the value of the input (in the same format specified in the plugin initialization). That will do the trick.
<!-- value specifid as mm-dd-yyyy -->
<input class="date" value="03-11-2018">

how do I format date when using pikaday

I am using pikaday module for datepicker, but the format comes as inappropriate format. I tried adding this line of code but still not working:
.config(['pikadayConfigProvider', function (pikaday) {
pikaday.setConfig({
numberOfMonths: 1,
format: "YYYY/MM/DD"
});
}])
This is how my html looks like:
<div class="modal-body">
<form role="form">
<div class="form-group">
<input type="text" class="form-control" pikaday="myPickerObject" name="time" ng-model="clas.class_.time" placeholder="Enter time" tabindex="3">
</div>
</form>
</div>
Also tried to add as an inline attribute
format = "yyyy/mm/dd"
still not working.
Any help
You can use moment.js and set the format by setting
defaultDate : moment().format("MMM YYYY")
this will be the initial input date display format.
For displaying/processing the date in other desired formats, use
var field = document.getElementById('datepicker');
var picker = new Pikaday({
onSelect: function(date) {
field.value = this.getMoment().format('Do MMMM YYYY');
}
});
use moment.js to set the date format:
var picker = new Pikaday(
{
field: document.getElementById('eDate'),
toString(date, format) { // using moment
return moment(date).format('MM/DD/YYYY');
},
});
quick update, if you don't want to use moment.js, you can fdo the following
new Pikaday({
field: document.getElementById('eDate'),
toString: function(date) {
var parts = [('0'+date.getDate()).slice(-2), ('0'+(date.getMonth()+1)).slice(-2), date.getFullYear()];
return parts.join("-");
}
})
this will produce 18-07-1980. You can change from '-' to '/' by changing return parts.join("-"); and you can rearrange parts to apply mm/dd/yyyy via parts array

Date Picker Highlight day if not Available

I have this online reservation, and i have this problem, Is there a way i can highlight the unavailable days on the date picker?assuming i have inserted dates on the database. Here's my code for the date picker.
<input type="text" name="pick-up-date" id="pick-up-date" class="form-control datepicker" placeholder="mm-dd-yyyy">
Here's a screenshot:
Use beforeShowDay() function from jQuery check this
e.g., something like this,
var datesToDisable = ["2015-01-07","2015-17-07","2015-21-07"]; //you have to fetch the dates and put em in an array and wh7atever the format is.
$('#pick-up-date').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [ datesToDisable.indexOf(string) == -1 ]
}
});
Should do the trick!

Validate date so that the date cannot be in future or in past

I have this form that has a date input. What is the best way in Javascript that I can ensure the value selected is neither a future date or a past date. I have implemented jQuery date picker to select date see code below
<html>
<!--maina-->
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="main.css" rel="stylesheet" type="text/css"/>
<script>
$(function() {
var date = $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
});
function ValidateForm(){
var date_of_circulation = document.forms["myForm"]["date_of_circulation"].value;
if (date_of_circulation == null || date_of_circulation ==""){
alert ("You have to select the date the manuscript was circulated");
return false;
}
}
</script>
<form enctype="multipart/form-data" name = "myForm" action = "" onsubmit="return ValidateForm()" method = "post">
Date of circulation:<input name="date_of_circulation" input type="text" id="datepicker"></p>
<input name = "add_manuscript" type="submit" value = "submit">
</form>
</html>
You can do it like this
var yourDate = new Date("12/5/2015"); //input value
var todayDate = new Date(); //Gets the today's date value
You have to use function setHours
if(yourDate.setHours(0,0,0,0) == todayDate.setHours(0,0,0,0));
{
//Do your stuff
}
NOTE: You can also do it using the jquery's datepicker
var currentDate = new Date();
$("#datepicker").datepicker("setDate", currentDate);
so that you can be sure that today's date is already selected.
EDIT: You can also look at datejs
datejs API Documentation
i found an effective and simple solution by introducing maxdate and mindate as explained here: date picker restrict date range. After rethinking the validation rules i decided that the logical validation for date_of_circulation value can be a date in the past but not exceeding current date and therefore changed var date in date picker to
var date = $("#datepicker").datepicker({ maxDate: new Date,dateFormat: 'yy-mm-dd', minDate: new Date (0) });
If date field must be set as current date, no future or past date than
set text field's default value to current date, you need not to use date picker as it's not user friendly to have a date picker without any other date option.
Also by doing this way, you need not to validate form on submit.
<input name="date_of_circulation" input type="text" id="datepicker" value="<?php echo date('Y-m-d'); ?>" readonly="readonly">
set input box as readonly so that user can not change the date.

Categories

Resources