Bootstrap datepicker multiple formats - javascript

I am using Backbone.js with a Bootstrap Datepicker in my form.
The brief was to allow the client to use the 'dd.mm.yyyy' format, so I set the option on the datepicker.
self.$el.find('[data-role="invoicedate"]').datepicker({
format: "dd.mm.yyyy",
todayBtn: "linked",
todayHighlight: true,
language: Application_language
});
Then the client wanted to allow 'dd.mm.yy' also, and to have it autotranslated, so I did the following:
invoicedateToModel: function() {
var invoicedate = this.$el.find('[data-role="invoicedate"]').val();
var re2 = /^(\d{2})\.(\d{2})\.(\d{2})$/;
if (re2.test(invoicedate)) {
invoicedate = invoicedate.replace(re2,"$1.$2.20$3");
}
var re4 = /^(\d{2})\.(\d{2})\.(\d{4})$/;
if (re4.test(invoicedate)) {
this.saveInvoiceDate(invoicedate);
this.displayInvoiceDate();
this.$el.find('[data-role="invoicedate"]').parent().toggleClass('has-error', false);
} else {
this.$el.find('[data-role="invoicedate"]').parent().toggleClass('has-error', true);
}
},
and bound it to the change event on the input. This worked fine, I now realize, because dd.mm.yy fits in the dd.mm.yyyy format, ie it does not contradict it.
Now the client wants to also be able to add ddmmyyyy as an entry option, but the datepicker autocorrects the form by replacing the newly entered date with the last known good one, or todays date, because ddmmyyyy does not match with dd.mm.yyyy, before the callback above gets called.
Is there any way to tell bootstrap-datepicker about multiple allowed formats?

You can pass functions to datepicker's format option. For really flexible parsing, I used moment.js.
$(".datepicker").datepicker({
format: {
toDisplay: function(date, format, language) {
return moment(date).format("MM/DD/YYYY");
},
toValue: function(date, format, language) {
return moment(date, ["DD.MM.YYYY", "DDMMYYYY"]).toDate();
}
}
});
From the bootstrap-datepicker docs:
toDisplay: function (date, format, language) to convert date object to string, that will be stored in input field
toValue: function (date, format, language) to convert string object to date, that will be used in date selection
You may have to play around with the moment() options, but you should be able to get it to where you want it. Check out momentjs's docs as well.

Related

Format LT datetimepicker : always returns today's date

I've to use the bootstrap datetimepicker for a legacy project.
With "LT" format, I've an issue, even if I set a default date, it returns the current date. (today).
check it on
codepen
$(function () {
$('#datetimepicker3').datetimepicker( {
defaultDate: moment("15/05/1992","DD/MM/YYYY"),
format: 'LT'
});
$('#datetimepicker3').on('dp.change',function(){
console.log('-');
console.log($('#datetimepicker3').data('DateTimePicker').date());
console.log($('#datetimepicker3').data('DateTimePicker').date().format('DD/MM/YYYY HH:mm'));
console.log('-');
});
});
I need to receive the date I set by default in datetimepicker.
Thanks.
I think the problem is exactly because you are using 'LT'. LT is a format of TIME-ONLY, so the information about the date is lost. That way, when it transform the "only time" information to a date or moment object, it uses the current date.
The defaultDate is to set the initial date/time for the component and not to define the date that will be used when dealing with time-only information.
My suggestion: take the value from the component (as you did), extract the time and then set the desired date for that time.
I hope it helps.

Bootstrap datetime picker remove meridian am/pm

I'm using asp.net MVC TextBoxFor to bind bootstrap-datetimepicker. It's working fine with simple input type text box.
But when I'm binding it with mvc textbox helper it's showing wrong year like '31/10/1899 00:00'
Then I got the solution somewhere to fix that.
$('.datetimepicker').datetimepicker({
format: "dd-mm-yyyy hh:ii:00P",
autoclose: true
});
It's working fine, but now It's adding meridians at the very end like AM/PM. I need to remove those AM/PM.
Any help would be appreciated.
Simply remove the P at the end of your foramt variable see below
format: "dd-mm-yyyy hh:ii:00",
try this:
$('.datetimepicker').datetimepicker({
autoclose: true,
showMeridian:false
});
As two previous answers said, to remove meridian you can combine both format and showMeridian usage:
$('.datetimepicker').datetimepicker({
format: "dd-mm-yyyy hh:ii:00",
autoclose: true,
showMeridian: false
});
However, there is a glitch when datepicker lost its focus without selecting anything or making incomplete selections, it reverts date back to December 31, 1899 (reproduced in this example fiddle). I managed to check bootstrap-datetimepicker.js file and found parseDate function causing this behavior:
parseDate: function (date, format, language, type, timezone) {
var parts = date && date.toString().match(this.nonpunctuation) || [],
// this line below represents December 31, 1899 (try using console.log)
date = new Date(0, 0, 0, 0, 0, 0, 0),
// -- skipped for brevity --
val, filtered, part;
// -- skipped for brevity --
}
A little tweak is possible by changing date assignment into current date:
parseDate: function (date, format, language, type, timezone) {
var parts = date && date.toString().match(this.nonpunctuation) || [],
date = new Date(),
// -- skipped for brevity --
val, filtered, part;
// -- skipped for brevity --
}
Note: This tweak only available for non-CDN script (installed through NuGet package or manually placed in Scripts folder).
Related issues:
Issue #494: Date set to '31 Dec 1899 00:00' when focus lost without selecting date
Issue #153

How to set specific timezone in datepicker using jquery only?

I've a field and applying datepicker on it using jQuery.
it is currently getting time from system/browser.
I want it to get time from specific time zone e.g America/new_york.
The endDate param is the key to set the calendar, means user should not be able to select the date from future. Currently it is looking like this
The code snippet is :
jQuery('#convo_start_date').datepicker({
format: 'dd M yyyy',
endDate: '+0d',
autoclose: true,
showButtonPanel: true,
todayBtn: 'linked'
}).on('change', function () {
jQuery('.datepicker').hide();
jQuery('#convo_end_date').attr('value',jQuery('#convo_start_date').val());
});
Question: Is there any way to set the default specific timezone like America/new_york to do not allow the date from future (according to this specific timezone)?
Note: I've tried moment.js but it is conflicting with my current work in jQuery, Is there any params datepicker library providesvto set with timezone?
If you are using jquery ui datepicker plugin, you can set the maxDate option to current date so that user can't select date from future.
You will need to do the conversion to the specific timezone. You can change the targetTimeOffset variable as per your requirement.
var d = new Date();
var targetTimeOffset = -4*60; //desired time zone, taken as GMT-4
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + targetTimeOffset );
Check Fiddle: http://jsfiddle.net/mpsingh2003/8w8v9/3387/ if this is what you are looking for
You can use Joda-Time library to get your solution.
Check the classes they provide like org.joda.time.DateTimeZone.
You can get the DateTimeZone depending on the Canonical ID defined in the Joda Time.
Please check this link for API documentation.
Hope this will helpful for you. Thanks.

Jquery datepicker change dateFormat to unix timestamp

I'm using the Jquery datepicker to add the selected dates to an SQL database in time format using dateFormat : '#'.
However, this uses js milliseconds and I need it in UNIX timestamp format which is in seconds. So basically I get an extra 3 zeros on the end.
I know I can /1000 to get the correct integer, but how do I do that in the js before it is entered into the db?
This is what I have so far:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.MyDate').datepicker({
dateFormat : '#'
});
});
</script>
try the below, it has temp value for your SQL DB.
var tempSQLvalue;
jQuery(document).ready(function() {
jQuery('.MyDate').datepicker({
dateFormat : '#',
onSelect: function(date) {
tempSQLvalue = date.slice(0,date.length-3);
console.log(tempSQLvalue);
}
});
})
Posting this answer for anyone else who has the same issue. Instead of using timestamps, I stuck to standard date formats. However, you need to check the different date formats between jquery and php. For example, the date 03-01-16 in jquery will be 'dd-mm-yy' while in php, the same date format would be 'd-m-Y'.

Why does changing the dateFormat of my jQuery datepicker fail?

I know there are loads of questions on here about changing the datepicker dateFormat, but i'm following the instructions exactly and they seem to have no effect. Here is the exact code that was suggested on other answers:
$(document).ready(function() {
$('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' });
});
Yet when I run it, and test the datepicker value with alert($('#datepicker').datepicker("getDate"));
I get the date back in the undesired format! This is extremely confusing. Am I something wrong? See the described behaviour at http://jsfiddle.net/TmdM8/
edit: even more confusing is that if I read the dateformat using alert($("#datepicker").datepicker('option', 'dateFormat'));
... the returned dateFormat is correct, even though calling getDate does not return the date in the desired format. See http://jsfiddle.net/fWmBe/
the date format setting is for what the format looks like when it's show in the text box the picker is applied to.
have a look at my updated version of your fiddle:
http://jsfiddle.net/TmdM8/1/
as you can see, when you pcick in the text box, and pick a date, it is in the format you have specified.
as far as i know, the getDate function returns a javascript date.
EDIT:
if you wanted to format the output from the javascript date, you'll need to use a custom script, or a library like date.js (i've had great success with this).
http://code.google.com/p/datejs/
with that you could do something like :
$('#datepicker').datepicker("getDate").toString('dd-MM-yyyy');
to get your date in the format you like
I agree that it returns a javascript date. You can use this utility function:
$.datepicker.formatDate( format, date, settings ) - Format a date into a string value with a specified format.
from http://docs.jquery.com/UI/Datepicker/formatDate
What is happening here is getDate is return a javascript date object. You are seeing the date object's toString method.
Try this:
$(document).ready(function() {
$('#datepicker').datepicker({
onSelect: function(dateText, inst) { alert(dateText) }
});
$('#datepicker').datepicker( "option" , 'dateFormat', 'yyyy-mm-dd' )
});
in case someone looking for this answer like me. here is a working code:
<script>
$(function() {
$( "#datepicker" ).datepicker({inline: true, dateFormat:'yy-mm-dd'}); });
</script>

Categories

Resources