Format date on bootstrap datetimepicker - javascript

I am using the Bootstrap 3 Date/Time Picker (https://github.com/Eonasdan/bootstrap-datetimepicker) and I have problems
formatting the date
<input type="text" id="fmEndDate" class="form-control input-sm"
datetimepicker
format="DD-MM-YYYY hh:mm"
ng-model="workRequest.EndDate"
placeholder="..."
name="fmEndDate"
required
ng-disabled="isDisabled">
But the value is being display as MM/DD/YYYY hh:mm AM
i want 31-12-2017 23:59 for new year eve timestamp
This is my directive
"use strict";
angular.module("datetimepicker", [])
.provider("datetimepicker", function () {
var defaultOptions = { };
this.setOptions = function (options) {
defaultOptions = options;
};
this.$get = function () {
return {
getOptions: function () {
return defaultOptions;
}
};
};
})
.directive("datetimepicker", [
"$timeout",
"datetimepicker",
function ($timeout,datetimepicker) {
var defaultOptions = datetimepicker.getOptions();
return {
require : "?ngModel",
restrict: "AE",
scope : {
datetimepickerOptions: "#"
},
link : function ($scope, $element, $attrs, ngModelCtrl) {
var passedInOptions = $scope.$eval($attrs.datetimepickerOptions);
var options = jQuery.extend({}, defaultOptions, passedInOptions);
$element
.on("dp.change", function (e) {
if (ngModelCtrl) {
$timeout(function () {
ngModelCtrl.$setViewValue(e.target.value);
});
}
})
.datetimepicker(options);
function setPickerValue() {
var date = options.defaultDate || null;
if (ngModelCtrl && ngModelCtrl.$viewValue) {
date = ngModelCtrl.$viewValue;
}
$element
.data("DateTimePicker")
.date(date);
}
if (ngModelCtrl) {
ngModelCtrl.$render = function () {
setPickerValue();
};
}
setPickerValue();
}
};
}
]);
Any ideas?

As shown in the bootstrap3 docs you can define custom formats in JavaScript:
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker3'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker3').datetimepicker({
format: 'your desired Formatting style'
});
});
</script>
</div>
</div>
Even more simple:
$("#fmEndDate").datetimepicker({format: 'dd-mm-yyyy hh:ii'});
Sidenote: Be careful with Date/Time formatting:
As for AngularJS HH format will result in hours as 00-23. While in Bootstrap3 which you are also using HH will result in hours as 01-12.
I highly suggest you to use a library like MomentJS which is doing the troublesome work for you.
Regards,
Megajin

Related

How to input only YYYY(Format year) in textbox using angularjs

<input type="date" id="exampleInput" name="input" ng-model="startYear"
placeholder="yyyy" min="1111" max="9999" />
I tried above way but didn't work
<div date-input ng-model="date"></div>
Your directive template would look like this:
<input
id="exampleInput"
type="number"
name="input"
ng-model="year"
ng-change="setDate()"
placeholder="yyyy"
min="1111"
max="9999"
/>
While your actual directive would look like:
.directive('dateInput', ['$filter', function($filter) {
return {
restrict: 'A',
scope: {
ngModel: '='
},
templateUrl: './dateInput.html',
link: function(scope) {
scope.$watch('ngModel', function(nv, ov) {
if (!angular.isDefined(nv) && !angular.isDefined(ov)) {
scope.ngModel = new Date();
scope.year = _getYear(scope.ngModel);
} else {
scope.ngModel = new Date(nv);
}
})
angular.extend(scope, {
setDate: setDate
})
function _getYear(date) {
return parseInt($filter('date')(date, 'yyyy'));
}
function setDate() {
var year = parseInt(scope.year),
date = new Date(year, 1, 1);
scope.ngModel = date;
}
}
}
}]);
So basic idea is to extract year from date input using angulars built in date filter or create new date object if value has not been passed and do the same thing.
Edit it and than compose a new date object and bind to ngModel.
You could easily do the same for month and day and replace 1 values that are passed to date object constructor.
Note that you also have to pass date formatted in a way Date object can read it.

ng-focus or ng-click is not working in Angular as expected

I have a text input field and a datepicker embedded in it. The problem is when we focus or even click on the input field
the date picker does not get showed.
But if you put a debugger and debug in console , it shows when the input field gets focused or clicked.
<div class="row">
<input id="field" placeholder="Choose Date" class="span-12" ng-model="vm.date" ng-blur="vm.onSaveTime()" ng-focus="vm.showDatePicker()">
</div>
Here is the code
vm.showDatePicker = function(){
debugger;
var options = {
format:"YYYY-MM-DD"
};
$('#field').datepicker(options);
}
The date picker does not show initially when the page loads and if you don't debug in console or if you do not click other fields in the panel and then after click on it .
Why is it so ?
It might be help you
<div id="wrapper" ng-app="myApp">
<p>{{datePicker || "00/00/0000"}}</p>
<input type="text" ng-model="datePicker" datepicker />
</div>
var myApp = angular.module('myApp', []);
myApp.directive("datepicker", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, elem, attrs, ngModelCtrl) {
var updateModel = function (dateText) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(dateText);
});
};
var options = {
dateFormat: "dd/mm/yy",
onSelect: function (dateText) {
updateModel(dateText);
}
};
elem.datepicker(options);
}
}
});
https://codepen.io/anon/pen/BWeWVp

Angularjs. TypeError: Cannot read property 'apply' of undefined

I have angularjs app with a form that has a dropdownlist and and a datetimepicker.
When I change the dropdownlist I want to update the date displayed in the datepicker.
I get the following error when I change selected item in the dropdownlist
TypeError: Cannot read property 'apply' of undefined
at HTMLInputElement.<anonymous> (bootstrap-datetimepicker.min.js:2)
at Function.each (jquery-3.1.1.min.js:2)
at r.fn.init.each (jquery-3.1.1.min.js:2)
at r.fn.init.a.fn.datetimepicker (bootstrap-datetimepicker.min.js:2)
at m.$scope.SymbolChanged (moduleConfigformController.js:29)
at fn (eval at compile (angular.js:15197), <anonymous>:4:159)
at m.$eval (angular.js:18017)
at angular.js:25775
at Object.<anonymous> (angular.js:28600)
at q (angular.js:357)
This is the offending line of code:
$("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
Here is my controller:
mainApp2.controller("moduleConfigformController",
function moduleConfigformController($scope, moduleConfigformService, $uibModalInstance) {
$scope.close = function (e) {
$uibModalInstance.dismiss();
e.stopPropagation();
};
$scope.formDebug = "loaded";
var settingsPromise = moduleConfigformService.simulationsettings();
settingsPromise.then(function (settings) {
$scope.simulationsettings = settings;
$scope.symbols = $scope.simulationsettings.symbols;
$scope.intervals = $scope.simulationsettings.intervals;
}).catch(function (error) {
throw error;
});
$scope.SymbolChanged = function () {
console.log("Symbol ddl changed");
console.log("New value is " + $scope.simulationsettings.Symbol);
// hardcoded date
// TODO: Find StartDate and EndDate where Symbol = $scope.simulationsettings.Symbol
$scope.simulationsettings.StartDate = "24/12/2014 8:26 PM";
// Display the new date in the datetimepicker
// This line produced the TypeError
$("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
console.log("startdate is " + $scope.simulationsettings.StartDate);
console.log("startdate is " + $scope.simulationsettings.EndDate);
}
$scope.submitConfigForm = function () {
console.log("configform submitted");
var startDate = $scope.simulationsettings.StartDate;
var endDate = $scope.simulationsettings.EndDate;
var symbol = $scope.simulationsettings.Symbol;
var interval = $scope.simulationsettings.Intervals;
$scope.formDebug = "StartDate: " + startDate + " EndDate: " + endDate + " Symbol: " + symbol + " Interval: " + interval;
}
});
Here is my form:
<form name="configForm" ng-submit="submitConfigForm()">
<div class="modal-header" style="text-align:center">
<h3 class="modal-title">Configure</h3>
<div style="margin-top:10px">
<button tabindex="100" class="btn btn-success pull-left" type="submit" ng-class="{'btn-primary':configForm.$valid}">Start analysis</button>
<button class="btn btn-warning pull-right" ng-click="close($event)">Close</button>
</div>
</div>
<div class="modal-body">
<div class="col-sm-6" style="width: 100%;">
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-3">Symbol</label>
<div class="col-sm-9">
<select ng-model="simulationsettings.Symbol" ng-change="SymbolChanged()" name="fmSymbols" id="fmSymbols">
<option ng-repeat="item in symbols" value="{{item.Symbol}}">{{item.Symbol}}</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">start date</label>
<div class="col-sm-9">
<input type="text" id="fmStartDate" class="form-control input-sm"
datetimepicker
ng-model="simulationsettings.StartDate"
placeholder="..."
name="fmStartDate">
</div>
</div>
</div>
form debug: '{{formDebug}}'
</div>
</div>
The datetimepicker directive
"use strict";
angular.module("datetimepicker", [])
.provider("datetimepicker", function () {
var defaultOptions = {};
this.setOptions = function (options) {
defaultOptions = options;
};
this.$get = function () {
return {
getOptions: function () {
return defaultOptions;
}
};
};
})
.directive("datetimepicker", [
"$timeout",
"datetimepicker",
function ($timeout,datetimepicker) {
var defaultOptions = datetimepicker.getOptions();
return {
require : "?ngModel",
restrict: "AE",
scope : {
datetimepickerOptions: "#"
},
link : function ($scope, $element, $attrs, ngModelCtrl) {
var passedInOptions = $scope.$eval($attrs.datetimepickerOptions);
var options = jQuery.extend({}, defaultOptions, passedInOptions);
$element
.on("dp.change", function (e) {
if (ngModelCtrl) {
$timeout(function () {
ngModelCtrl.$setViewValue(e.target.value);
});
}
})
.datetimepicker(options);
function setPickerValue() {
var date = options.defaultDate || null;
if (ngModelCtrl && ngModelCtrl.$viewValue) {
date = ngModelCtrl.$viewValue;
}
$element
.data("DateTimePicker")
.date(date);
}
if (ngModelCtrl) {
ngModelCtrl.$render = function () {
setPickerValue();
};
}
setPickerValue();
}
};
}
]);
Any idea how to update the datetimepicker so it displays the updated value?
You are updating the model here:
$scope.simulationsettings.StartDate = "24/12/2014 8:26 PM";
Then you try to set the datepickers value here:
$("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
But the datepicker has $scope.simulationsettings.StartDate as model. This is why you get the error. Angular is trying to call the digest cycle twice.
Your function should look like this:
$scope.SymbolChanged = function () {
console.log("Symbol ddl changed");
console.log("New value is " + $scope.simulationsettings.Symbol);
// hardcoded date
// TODO: Find StartDate and EndDate where Symbol = $scope.simulationsettings.Symbol
// the binding should be of the same type as your input, it means that the value returned from the datepicker must be a Date
$scope.simulationsettings.StartDate = new Date("24/12/2014 8:26 PM");
// This line is useless, the datepicked model is binded to $scope.simulationsettings.StartDate
// $("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
console.log("startdate is " + $scope.simulationsettings.StartDate);
console.log("startdate is " + $scope.simulationsettings.EndDate);
}
But since you are using an input type="text" we need more information on the datetimepicker directive that you are using.
your are trying to put a date object in text field which may work if you're not using a date-picker
1/ change your input type to type date or change this $("#fmStartDate").datetimepicker("setDate", new Date($scope.simulationsettings.StartDate));
to this $("#fmStartDate").datetimepicker("setDate", $scope.simulationsettings.StartDate);
and it may work if your date-picker accepts this format "24/12/2014 8:26 PM"
2/ you may wanna check the date-picker documentation for the accepted format types

ng-model doesn't get updated in directive template

I have build some kind of date picker with modal window. I have strange problems with the code. My scenario is like this, the user pick a range: start-date and end-date, then a pop up window is displayed. we displayed a variety of data which can be choose via radio box. The radio box is wired with ng-model:
<td><input class="dga_radio" type="radio" name="dga" value="{{$index}}" ng-model="selectedDga" />
</td>
apparently I suppose to get the index into selectedDga which is a scope variable.But what I see that no value is get inside that variable at all.
I am adding the entire code here:
The directive:
angular.module('directives', [])
.directive('datepicker', ['$timeout', 'dataFactory', function ($timeout, dataFactory) {
// Runs during compile
return {
scope: {
id: '#',
"class": '#',
onSelectStartDate: '&',
onSelectEndDate: '&',
onSelectGoMode: '&',
},
restrict: 'E',
templateUrl: 'Templates/datepicker.html',
replace: true,
link: function ($scope, iElm, iAttrs, controller) {
$scope.selectedDga;
var startDate, endDate;
$scope.selectStartDate = function (time) {
if (angular.isFunction($scope.onSelectStartDate())) {
$scope.onSelectStartDate()(time);
}
console.log('$scope.startDate', $scope.startDate);
}
$scope.selectEndDate = function (time) {
if (angular.isFunction($scope.onSelectEndDate())) {
$scope.onSelectEndDate()(time);
}
console.log('$scope.endDate', $scope.endDate);
}
//define blackout and close click callbacks.
$("#blackout, .close").click(function () {
$("#blackout").removeClass("visable");
$("#popup").removeClass("visable");
});
$("#GoBtn").click(function () {
if (angular.isFunction($scope.onSelectGoMode())) {
$scope.onSelectGoMode()();
}
var wmessage_container = $('#warning-message');
var wmessage = $('#warning-message > #wmessage');
startDate = $("#datepicker-start").val();
endDate = $("#datepicker-end").val();
console.log('reach here!');
if ((angular.isDefined(startDate) && startDate != '') && (angular.isDefined(endDate) && endDate != '')) {
console.log('case 1');
//check if startDate and endDate are valid
if (startDate > endDate) {
wmessage_container.show();
wmessage.text('start date and end date values are invalid!');
console.log('startDate is bigger than end date');
}
else {
var promise = dataFactory.getDGAList(startDate, endDate);
promise.then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log('success callback');
console.log('response.status ', response.status);
console.log('response.data', response.data);
console.log('response.headers', response.headers);
console.log('response.config', response.config);
if (response.status == 200) {
$scope.collection = response.data;
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('promise callback');
console.log('response.data', response.data);
console.log('response.headers', response.headers);
console.log('response.config', response.config);
});
wmessage.text('');
wmessage_container.hide();
}
//call DataFactory service.
} else {
wmessage_container.show();
if ((startDate == '' || !angular.isDefined(startDate)) && (endDate == '' || !angular.isDefined(endDate)))
{
console.log('case 2');
wmessage.text('start date and end date are required !');
}
else if (startDate == '' || !angular.isDefined(startDate)) {
console.log('case 3');
wmessage.text('start date is required !');
} else {
console.log('case 4');
wmessage.text('end date is required !');
}
}
console.log('startDate', startDate);
console.log('endDate', endDate);
$("#blackout").addClass("visable");
$("#popup").addClass("visable");
});
var actions = [$scope.selectStartDate, $scope.selectEndDate];
$(".date-wrapper").each(function (index) {
console.log('directive index', index);
console.log('actions:', actions);
$input = $(this).find('input');
$btn = $(this).find('.calendar');
console.log('input', $input[0]);
console.log('btn', $btn[0]);
var counter = 0;
var updateTime = $scope.selectDate;
$input.attr('type', 'text');
var pickerStart = new Pikaday({
field: $input[0],
trigger: $btn[0],
container: $(this)[0],
format: 'DD/MM/YYYY',
firstDay: 1,
onSelect: actions[index]
});
$btn.show();
counter++;
});
}
};
}]);
The template:
<div id="{{id}}" class="{{class}}">
<div id="date-start-wrapper" class="date-wrapper">
<label for="datepicker-start" class="datepicker-lbl">From:</label>
<div class="fieldWrapper">
<input id="datepicker-start" type="date" placeholder="Select date" />
<a class="calendar"></a>
</div>
</div>
<div id="date-end-wrapper" class="date-wrapper">
<label for="datepicker-end" class="datepicker-lbl">To:</label>
<div class="fieldWrapper">
<input id="datepicker-end" type="date" placeholder="Select date" />
<a class="calendar"></a>
</div>
</div>
<button id="GoBtn" class="btn btn-primary btn-md">GO</button>
<div id="blackout"></div>
<div id="popup">
<span class="close"></span>
<div id="content">
<table cellpadding="10" cellspacing="10" border="1">
<tr>
<th></th>
<th>Id</th>
<th>Source</th>
<th>IsValid</th>
<th>Sampling Date</th>
</tr>
<tr ng-repeat="item in collection">
<td><input class="dga_radio" type="radio" name="dga" value="{{$index}}" ng-model="selectedDga" />
</td>
<td ng-repeat="(key,value) in item">
{{value}}
</td>
</tr>
</table>
selected_dga:{{selectedDga}}
</div>
<div id="warning-message">
<img src="../images/sign.png" width="32px" height="32px" />
<span id="wmessage" ></span>
</div>
<button id="okbtn" class="btn btn-success btn-md">ok</button>
<button id="cancelbtn" class="btn btn-danger btn-md">cancel</button>
</div>
</div>
If I am trying this in a simple directive then everything works like a charm, but in my current directive I don't get any value.
Calling the directive is something like this:
<datepicker id="thedatepicker" class="dates-wrapper" on-select-start-date="onSelectedStartDate" on-select-end-date="onSelectedEndDate" on-select-go-mode="Go" ></datepicker>
The answer is simple: I shouldn't use primitive in the ng-model.
Only adding exemple to #Brk answer:
It's just changing the primitive for an object. In my case:
In the controller:
$scope.name = 'Any Name' --> $scope.person = { 'name' : 'Any Name' };
In the directive:
ng-model="name" --> ng-model="person.name"
Simple like that!

On change of value in datetimepicker it should update another text area

I am new to bootstrap and trying to use it and I am trying to do below mentioned.
My datetime picker control 1
<div class='input-group date' id="reportdate">
<input type='text' class="form-control" value="#Model.ReportDate.ToString("dd/MM/yyyy")"/>
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
My date time picker control 2
<div class='input-group date' id="fromdate">
<input type='text' class="form-control" value="#Model.RecievedFrom.ToString("dd/MM/yyyy")"/>
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
What I am trying to do?
On change of the value from my date time picker control 1 it should change the value in datetimepiker control2.
What I did?
My main.js class which is handling all these functions.
var main = main || {};
main.functions = function() {
function changeDates() {
***// I am trying to change the value of my datetime picker control2 here.
var val = $(this).val;
alert(val);***
}
return {
changeDates: changeDates
};
}();
main.Loader = function () {
//-- Entry point
function init() {
var $body = $("body");
loadDatePickers($body);
loadTimePickers($body);
}
//-- Load date time pickers
function loadDatePickers($context) {
var $datePickers = $context.find(".date");
if ($datePickers.length) {
$datePickers.each(function () {
$(this).datetimepicker({ language: 'en-gb', pickTime: false });
if ($(this).attr("id") == "reportdate") {
$(this).change(function () {
main.functions.changeDates();
});
}
});
}
}
function loadTimePickers($context) {
var $timePickers = $context.find(".time");
if ($timePickers.length) {
$timePickers.each(function () {
$timePickers.datetimepicker({ language: 'en-gb', pickDate: false });
});
}
}
return {
init: init
};
}();
$(document).ready(function () {
main.Loader.init();
});
Any help would be much appreciated.
You can use .change event for that,
$("#reportdate").find(".form-control").change(function () {
$("#fromdate").find(".form-control").val($(this).val());
});

Categories