I know how famous is this topic … but my question is a little bit more complex.
I read documentation here
I want to display date in french format (dd/mm/yyyy) and save value in US format (yyyy-mm-dd).
I also need to specified startDate which is first day of month.
I tried this configuration :
$(document).ready(function() {
$('#datepicker').datepicker({
format: {
language: 'fr',
toDisplay: function(date, format, language) {
return date.getUTCDate() + "/" + (date.getUTCMonth() + 1) + "/" + date.getUTCFullYear();
},
toValue: function(date, format, language) {
return new Date(date);
}
},
//startDate: function(date) {
// return date.getUTCFullYear() + "-" + date.getUTCMonth() + "-01";
//},
autoclose: true,
todayHighlight: true,
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker3.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet" />
<input type="text" id="datepicker" />
But :
- Display Value : not really french format … 7/9/2016 instead of
07/09/2016 - StartDate : doesn’t work
Anyone could help me please ?
3
Answers
Try using moment.js, it has a ton of time formatting logic, it’s lightweight, easy to use, and has locale support.
http://momentjs.com/
Get value split it on “/” en rejoin them afterwards.
Then you can edit each part afterwards as you want.
You can follow i18n docs, if you want to localize you picker. Basically you have to import an additional js file with locale specific settings and then specify the
language
option. This way you automatically customize displayed format.Use the
format: 'dd/mm/yyyy'
if you just want to change the format. (E.g. No french names for months and days)You don’t need
toDisplay
andtoValue
to convert your date into the desiredYYYY-MM-DD
format, you can use an helper function as shown in the example below.Note that
startDate
docs says that:The one in your example probably isn’t parsable due to
-
.Finally, I suggest to use momentjs to simplyfy both first day of month calculation and format conversion. Here there is a working example using moment and datepicker’s i18n: