I am working on an angularjs web application which uses REST layer to communicate with the backend. I have to display the date and time of a job but I receive it in milliseconds format. How do I convert the value to display the date and time on the UI.
1479982860000 // input
11/24/16 //output date
10:21 AM //output time
Both have to be stored in DataModel.date and DataModel.time.
Also the user enters a date and a time which I have to combine and send it in the same milliseconds format to the REST layer. How do I do that?
<input type="time" id="exampleInput1" ng-model="DataModel.time"
placeholder="HH:mm:ss" required/>
<input type="date" id="exampleInput2" ng-model="DataModel.date"
placeholder="yyyy-mm-dd" required/>
I have to combine the two and send it as Datamodel.date in the controller. Please help.
According to the documentation, you can convert the value in your controller.
$scope.date = new Date($scope.DataModel.time);
$scope.date= $filter('date')(new Date($scope.DataModel.time), 'yyyy-mm-dd');
and the view:
<input type="date" id="exampleInput2" ng-model="date" placeholder="yyyy-mm-dd" required/>
Don't forget to add $filter in your dependencies:
app.controller('YourController', ['$scope','$filter', function($scope, $filter) {
}]);
[This may work for your issue]
https://docs.angularjs.org/api/ng/filter/date
Here is a simple example to achieve what you need,
use
(new Date($scope.milli_seconds)) to get the full date.
(new Date($scope.milli_seconds)).toDateString() to get the date from it
(new Date($scope.milli_seconds)).toTimeString() to get the time from it
(new Date($scope.milli_seconds)).getTime() to convert bact to milliseconds
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
"milliseconds" : {{milli_seconds}} <br>
"full_date" : {{full_date}} <br>
"date" : {{date}} <br>
"time" : {{time}} <br>
"millisecondsreverse" : {{milli_seconds_reverse}} <br>
<br><br>
<input type="time" id="exampleInput1" ng-model="DataModel.time"
placeholder="HH:mm:ss" required/>
<input type="date" id="exampleInput2" ng-model="DataModel.date"
placeholder="yyyy-mm-dd" required/>
<input type="submit" ng-click="submit_values()" value="getmilliseconds"/> <br>
<span ng-if="milli">Your milliseconds: {{milli}}</span>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.DataModel = {}
$scope.milli_seconds = 1479982860000;
$scope.full_date = (new Date($scope.milli_seconds))
$scope.date = $scope.full_date.toDateString()
$scope.time = $scope.full_date.toTimeString()
$scope.milli_seconds_reverse = $scope.full_date.getTime();
$scope.submit_values = function()
{
date = new Date($scope.DataModel.time).toTimeString()
time = new Date($scope.DataModel.date).toDateString()
date_time = (new Date($scope.DataModel.date).toDateString())+" "+ (new Date($scope.DataModel.time).toTimeString())
alert(new Date(date_time).getTime());
$scope.milli = new Date(date_time).getTime();
}
});
</script>
</body>
</html>
Please run the above snippet
You can just convert it into different formats you like, using the filters.
Here is a fiddle
Have a look at moment.js
Add configuration in your JS file
/*Configuration to change the date format*/
angular.module('myapp')
.config(function($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return date ? moment(date).format('DD/MM/YYYY') : '';
};
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'DD/MM/YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
})
Change the format which ever way you want
var newFormatDate =moment(oldFormatDate).format();
EDITS
If you want to set specific timezone,
moment().tz("America/Los_Angeles");
MOMENT.JS DOCS
Also look at timezone identifier
Related
I am trying to set initial value of datepicker to be the time on the chart where the user clicked. The value is being stored in the variable used in ng-model but the it still displays the placeholder instead.
<input class="form-control" ng-init="vm.input" ng-model="vm.input" ng-model-options="{ updateOn: 'blur' }" placeholder="Click here to select a date"
moment-picker="vm.input" style="width:25em;height:25px;" format="LL LTS">
in controller I am passing the value to be displayed initially:
scope.vm.input = moment(xScale.invert(newData[0])).format("ddd MMM D YYYY HH:mm:ss z");//Sun Feb 18 2018 05:16:29
Am I missing something ? I tried the solution given in this question: How to set today date and time as default in angular-moment-picker . But it didn't work for me.
Your mistake is using scope and vm as this together in controller, description is:
<div ng-controller="ctrl as vm">
{{vm.input}}
</div>
app.controller("ctrl", function() {
var vm = this;
//do not use scope.vm, vm is scope for this controller
vm.input = "Hello World";
})
var app = angular.module("app", []);
app.controller("ctrl", function() {
var vm = this;
vm.input = moment().format("ddd MMM D YYYY HH:mm:ss z");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as vm">
<input class="form-control" ng-init="vm.input" ng-model="vm.input" ng-model-options="{ updateOn: 'blur' }" placeholder="Click here to select a date"
moment-picker="vm.input" style="width:25em;height:25px;" format="LL LTS">
</div>
I am new to Angular JS and I am trying to implement validation for date time picker in my Angular project.
I am using bootstrap date picker.
My HTML is :
<div>
<form id="edit-profile" novalidate name="editReservationForm" autocomplete="off" class="form-horizontal">
<fieldset>
<div class="control-group">
<label class="control-label" for="reservation.reservedFrom">Reserved From<sup>*</sup></label>
<div class="controls input-group date" data-provide="datepicker">
<input type="text" class="span4" style="width:150px" name="reservedFrom" placeholder="Reserved From" data-ng-model="reservation.reservedFrom"
validator="required" required-error-message="Date is required" valid-method="watch" id="startDate"/>
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div> <!-- /controls -->
</div> <!-- /control-group -->
<div class="control-group">
<label class="control-label" for="reservation.reservedTill">Reserved Till<sup>*</sup></label>
<div class="controls input-group date" data-provide="datepicker">
<input type="text" style="width:150px" class="span4" name="reservedTill" placeholder="Reserved Till" data-ng-model="reservation.reservedTill"
validator="required" required-error-message="Date is required" valid-method="watch" id="endDate" ng-change='checkErr(startDate,endDate)'/>
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
<span>{{errMessage}}</span>
</div> <!-- /controls -->
</div> <!-- /control-group -->
</fieldset>
</form>
</div>
My Controller is :
myApp.controller('editReservationController', ['$scope', '$filter', 'reservationResolved', 'pocResolved', 'accountResolved', 'reservationServices', '$location', '$state',
function ($scope, $filter, reservationResolved, pocResolved, accountResolved, reservationServices, $location, $state) {
$scope.reservation = new Object();
$scope.accounts = accountResolved.data;
$scope.pocs = pocResolved.data;
$scope.reservation.employee = reservationResolved.data;
$scope.updateReservation = function () {
if ($scope.editReservationForm.$valid) {
reservationServices.updateReservation($scope.reservation).then(function (result) {
$scope.data = result.data;
if (!result.data.error) {
$state.transitionTo('employeeTalentPool', {
id: $state.params.id
});
}
});
}
};
$scope.checkErr = function (startDate, endDate) {
$scope.errMessage = '';
var curDate = new Date();
if (new Date(startDate) > new Date(endDate)) {
$scope.errMessage = 'End Date should be greater than start date';
return false;
}
if (new Date(startDate) < curDate) {
$scope.errMessage = 'Start date should not be before today.';
return false;
}
};
$scope.cancel = function () {
$location.path("/reservations");
}
}]);
I am totally new to Angular and I'm trying to understand it by doing projects. Can anyone have a check and provide a solution?
There is no need to pass in the startDate and endDate variables into the ng-change method on your second datepicker; you are already tracking those variables on your $scope with ng-model.
$scope.checkErr = function() {
var start = new Date($scope.reservation.reservedFrom),
end = new Date($scope.reservation.reservedTill);
if (end < start) {
$scope.errorMsg = "End must be after start";
}
... other logic ...
};
Additionally, it may be best to just prevent a user from making bad choices.
The two errors you seem to want to guard against are: 1) the user chooses a startDate before today and 2) the user chooses an endDate before the startDate.
Both of the errors above can be prevented by modifying the minDate option within datepicker-options. Check out the $watch in this plunker -- each time we select a new start date, we can modify the minDate option for the end date and prevent user input issues.
Update (per request)
The plunker shows two datepickers, both of which have their own custom datepicker-options bound as $scope variables -- we'll be able to modify these datepicker-options to change the behavior of each datepicker.
Defaulting startDateOptions "minDate" to today (within the CTRL) makes it impossible for a user to pick a startDate before today (solving the first issue you were trying to prevent).
Placing a $watch on the startDate allows us to update the endDateOptions after any a change of the startDate. This allows us to restrict a users choices for the endDate input by setting minDate to whatever the startDate is (solving the second issue of choosing an endDate before a startDate).
There is also some logic in the $watch to adjust endDate where it makes sense (like if we first selected a valid endDate, but then selected a new startDate that would make that endDate invalid).
In Angular (1.3), I want to be able to enter a dob field of my person object and this has another property called age which calculates the age based on the dob.
So I have the field to enter dob as:
<div class="form-group">
<input class="form-control" type="date" ng-model="player.dob" placeholder="DD/MM/YYYY" />
</div>
and I display some of the information that the user types, as they type (name, sex, description etc) but when the user enters the dob, I want to automatically display age like this:
<div>{{player.age}}</div>
How can I do that?
Thanks
I don't know if it's what you're looking for, but if I'm correct you can create a custom filter to display the age based on the dob input, as below:
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.player = {};
})
.filter('ageFilter', function() {
return function(dob) {
var ageDifMs = Date.now() - new Date(dob).getTime();
var ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
};
});
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div class="form-group">
<input class="form-control" type="date" ng-model="player.dob" placeholder="DD/MM/YYYY" />
</div>
<hr>
<div ng-if="player.dob" ng-bind="player.dob | ageFilter"></div>
</body>
</html>
you can use ngChange
<div class="form-group">
<input class="form-control" type="date" ng-model="player.dob" ng-change="calculateAge()" placeholder="DD/MM/YYYY" />
and then in your controller:
$scope.calculateAge = function(){
//do the calculations you want
}
I am using the following pattern to validate email
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/igm;
Copied the pattern from this fiddle. (http://jsfiddle.net/jquery4u/5rPmV/) which works wonderful.
I tried implementing the same with AngularJS like this
<input type="text" placeholder="Email" ng-model="Employer.Email" ng-pattern="emailPattern" class="form-control" name="email" required />
<p ng-show="showMessages && registerEmployerForm.email.$error.required" class="text-danger">
Email is required.
</p>
<p ng-show="showMessages && !registerEmployerForm.email.$error.required && registerEmployerForm.email.$error.pattern" class="text-danger">
Email is invalid.
</p>
JavaScript
$scope.showMessages = true;
$scope.Employer = {
"Email": ""
};
$scope.emailPattern = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/igm;
$scope.RegisterEmployer = function(myForm) {
console.log(myForm)
};
My Fiddle: http://jsfiddle.net/codeandcloud/jusoqs88/
The problem is that if I try naveen#naveennaveen.com, the first fiddle passes and the second fiddle fails. My questions
Why for the same pattern AngularJS behaves differently?
Is there something with my code?
P.S: I know input type="email" combined with registerEmployerForm.email.$error.email is the Angular way to do it. Unfortunately I cannot implement it here as the regex should not pass something like naveen#naveennaveen
Here is regexp for email validation:
var re = /^[a-z]+[a-z0-9._]+#[a-z]+\.[a-z.]{2,5}$/;
UPDATE
I can see this is not working in fiddle with 2 dots after #, but here it works : regex test online
UPDATE2
Looks like something wrong with fiddle, try this in your code, it will work:
var re = /^("")("".+?(?<!\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'*\+=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))([)([(\d{1,3}\.){3}\d{1,3}])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9])$/
<link rel="stylesheet" href="http://mbenford.github.io/ngTagsInput/css/ng-tags-input.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src="http://mbenford.github.io/ngTagsInput/js/ng-tags-input.min.js"></script>
<script>
var app = angular.module('ngApp', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $http) {
$scope.tags = [
{ text: 'abdo#tatwerat.com' },
{ text: 'info#tatwerat.com' },
{ text: 'admin#tatwerat.com' }
];
});
</script>
<div ng-app="ngApp" ng-controller="MainCtrl">
<tags-input ng-model="tags" placeholder="Add Emails" allowed-tags-pattern="^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$"></tags-input>
<p>Emails : {{tags}}</p>
</div>
I have a form that user will have to fill in. Some fields are dates and i don't want user to have to type in today's date.
My Form
<div class="row" ng-controller="JobOrderController as jOrder">
<form class="form-inline" ng-submit>
<div class="form-group">
<label for="todaysDate"><h4><span class='glyphicon glyphicon-flag'></span> Date</h4>Date </label>
<input type="text" class="form-control" id="todaysDate" ng-model="jOrder.orderData.date" value="{{ 2 + 4 }}" >
</div>
......... more code .........
My Controller
angular.module('jobOrderCtrl', ['jobOrderService'])
.controller('JobOrderController', function(Jobs, socketio) {
var vm = this;
vm.createOrders = function() {
vm.message = '';
Jobs.createOrders(vm.orderData)
.success(function(data) {
vm.orderData = '';
vm.message = data.message;
});
};
});
I try out using js to write to that date input field, but is not showing due to angular data binding.
So what i want is the date input value field to be today's date. So how do i go about and do this?
Where do you set the date?
orderData should be an object with the form fields - NOT a string
initialize the orderData:
var vm = this;
vm.orderData = { date : new Date()};
and remove the value property form the html input field. Also set type to date
<input type="date" class="form-control" id="todaysDate" ng-model="jOrder.orderData.date" >