Using Javascript slice inside angular expression - angularjs

I receive a number representing a date in ddmmyy format eg.: 250615 i need transform into this format : 25/06/15.
I canot use the angular date filter because i receive a number.
I try to use slice in this way but only print the first number
{{ singularitem.Dia.slice(0,2)}} {{ singularitem.Dia.slice(2,2) }} {{ singularitem.Dia.slice(-2,2) }}
How can it be done ?
ThankĀ“s in advance

Since you can't use the date filter, just create your own filter, doing whatever you want it to do:
app.filter('transformDate', function() {
return function(date) {
// Split string at every second character and combine them again with a `/` in between
return date.match(/.{1,2}/g).join('/');
}
})
Usage:
{{date | transformDate}}
Plunker: http://plnkr.co/edit/uBeT0eHOoAlHDUWydOpM?p=preview

You can go for a vanilla javascript function. If your format is always dd/mm/yy check this function:
(function () {
var date = "250615";
date = date.slice(0, 2) + "/" + date.slice(2,4) + "/" + date.slice(4,6);
console.log(date);
})()
FIDDLE

Slice is a prototype function of Strings and Arrays, not numbers. You need to convert your number to string first.
If you want to convert that number to a date object, you'd need:
function parseDate(dateAsNumber) {
var dateAsString = "" + dateAsNumber;
var day = Number(dateAsString.substr(0, 2));
//months are index 0
var month = Number(dateAsString.substr(2,2)) - 1;
//assumming all dates are 2000+ since you only get 2 digits
var year = Number(dateAsString.substr(4,2)) + 2000;
var date = new Date(year, month, day);
return date;
}
Calling parseDate(250615) returns Thu Jun 25 2015 00:00:00 GMT-0700 (Pacific Daylight Time)

Related

Add date format into date regex

I am getting date format like this /Date(1495111091673)/.I have created one custom filter to change date format.
app.filter('jsonDate', function () {
return function (date) {
return new Date(date.match(/\d+/)[0] * 1);
}
})
This filter returns date like this.
Thu May 18 2017 18:08:11 GMT+0530 (India Standard Time)
But I want it as standard format like dd/MM/yyyy so I have edited my filter code like this:
app.filter('jsonDate', function () {
return function (date) {
return new Date(date.match(/\d+/)[0] * 1, 'dd MMMM # HH:mm:ss');
}
})
Is it correct?
This filter returns date like this
Thu May 18 2017 18:08:11 GMT+0530 (India Standard Time)
No it doesn't, that's just how your console (or whatever) is choosing to display the Date instance (via Date.prototype.toString()).
I'd just use AngularJS's date filter ~ https://docs.angularjs.org/api/ng/filter/date.
For example (where dateFormat is your "/Date(1495111091673)/" formatted string)
{{dateFormat | jsonDate | date : 'shortDate'}}
Or in JS
let parsed = $filter('jsonDate')(dateFormat)
let dateString = $filter('date')(parsed, 'shortDate')
or via DI
.controller('controllerName', ['dateFilter', 'jsonDateFilter',
function(dateFilter, jsonDateFilter) {
let dateString = dateFilter(jsonDateFilter(dateFormat), 'shortDate')
}])

Angularjs Django compare dates

I am fetching the date from my Django backend which comes like this: 2016-03-31
In my angular controller I want to compare it with today's date and if they are similar I want to deactivate a button.
I tried new Date() which gives me something like Thu Mar 31 2016 08:59:01 GMT+0200 (W. Europe Daylight Time)
How can these two dates be compared to achieve my goal?
ehhhhh... i think currently we could only do a manual formatting
see this one: How to format a JavaScript date
For your reference, below is what i did though:
$scope.formatDate = function(date){
var newDate = new Date(date);
var year = newDate.getFullYear();
var month = (newDate.getMonth() + 1).toString(); //add 1 as Jan is '0'
var day = newDate.getDate().toString();
month = month.length > 1? month: '0'+month;
day = day.length > 1? day: '0'+day;
$scope.date = day + '/' + month + '/' + year;
}
If you want to compare the date with now you can do the following:
var now = new Date().getTime();
var compareDate = new Date('2016-03-31').getTime();
if(now > compareDate){
//greater
}else if(now < compareDate){
//less
}else{
//equal
}
Just add what you need to the scope and then you could do something like:
ng-disabled="compareDate === today"

convert 24 hour time to am/pm using angularjs filter

I have a value
$scope.time = 13:30:00 (in 24 hour format)
Now I want to change this value to am/pm format using angularjs filter like
<th class="text-center">{{time | any filter}}</th>
Output: 1:30 pm
Is there any built in filter or do I have to create custom filter?
how can I use "date" filter to solve this issue?
{{time | date:"h:mma"}}
Here are the formats.
Try
$scope.time = 2016-03-28T13:30:00
instead of $scope.time = 13:30:00
html use
{{d.date | timeDate}}
js filter
app.filter('timeDate', function() {
return function(value){
value = new Date(value);
return (value.getHours()>=13?(value.getHours()-12):(value.getHours())) + ":" + (value.getMinutes()<10?'0':'') + value.getMinutes() + (value.getHours()>11?'pm':'am');
}
});
this will convert
"Fri Nov 16 12:35:42 MST 2018"
to
"12:35pm"

angular filter on click by 'last week' data

Hi I am new in angular and making my first module. This article is very helpfull. I want to filter my data by lastweek records. I have already found days by current date and given date in mysql query, On button click I am just setting value like DisTopic=1 and this works fine.
May you please tell me how can I apply filter for a range like day>=1 && day<=7
I am using below:-
filter:{'topic': DisTopic,'attachment':attch, 'days':day}
Please help me.
Solution 1: with angular-filter module
As stated by other users, you could indeed do that with a custom filter. However, if you find yourself writing a lot of custom filters, I'll advise you have a look at angular-filter module. With this module you can do what you need with the pick filter :
<div ng-repeat="task in tasks | pick: 'days >= 1 && days <= 7'">{{task.name}}</div>
See demo fiddle
Solution 2: Custom filter with parameters
Template:
<div ng-repeat="task in tasks | dayFilter: 1 : 7">{{task.name}}</div>
Javascript:
app.filter('dayFilter', function() {
return function(input, startDay, endDay) {
var filterFunction = function (item) {
return item.days >= startDay && item.days <= endDay;
};
return input.filter(filterFunction);
};
});
See updated demo fiddle
Custom filter example, you can modify as per your need.
Controller
$scope.search = function (item) {
if ($scope.searchUser == null || $scope.searchUser.trim() == "")
return true;
if (item.FirstName.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1 || item.LastName.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1 || item.Role.toLowerCase().indexOf($scope.searchUser.toLowerCase()) != -1) {
return true;
}
return false;
};
and than call it in your view
| filter:search
So, depending on your requirement, you can pass as many parameters and modify method in controller.
//Below code solve my problem.
Date.prototype.getWeek = function () {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week
// with the first thursday of that year.
// Set the target date to the thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first thursday of the year
// First set the target to january first
target.setMonth(0, 1);
// Not a thursday? Correct the date to the next thursday
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The weeknumber is the number of weeks between the
// first thursday of the year and the thursday in the target week
return Math.ceil((firstThursday - target) / 604800000) - 1; // 604800000 = 7 * 24 * 3600 * 1000
};

AngularJs filter sql timestamp "yyyy-MM-dd HH:mm:ss" to something else

I've tried the angular docs of {{someDate | date:'params'}}, however; This doesn't work if someDate is in this format yyyy-MM-dd HH:mm:ss.
How would I convert yyyy-MM-dd HH:mm:ss to say just yyyy using angularjs.
The date filter is designed to handle multiple input types including date objects and common date strings. If your date string is not recognized by the provided date filter, I would just write my own filter. It would look something like this...
myapp.filter('toYear', function () {
return function (dateString) {
var dateObject = new Date(dateString);
return dateObject.getFullYear();
};
});
You can use it like this...
{{someDate | toYear}}
You can define a custom format as follows
Date.prototype.customFormat = function(){
return this.getMonth() +
"/" + this.getDate() +
"/" + this.getFullYear();
}
//usage
> var d = new Date()
Fri Mar 14 2014 15:39:07 GMT+0000 (GMT Standard Time)
> d.customFormat()
'2/14/2014'
More details https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
I actually fixed the solution here:
app.filter('timestampToISO', function() {
return function(input) {
input = new Date(input).toISOString();
return input;
};
});
http://bit.ly/1iJAV8G
UPDATE:
To implement you add this to the view:
{{someSQLTIMESTAMP | timestampToISO | date}}
Angular js date object doesn't support to convert from MySql date format to timestamp directly. So need to convert it to acceptable format from YYYY-mm-dd H:i:s to YYYY/mm/dd H:i:s and then convert it to a timestamp.
You may try the below snippet to convert Mysql date format YYYY-mm-dd H:i:s to timestamp using AngularJs filter
app.filter("mysqlDateFormatToTimestamp", function(){
return function(date){
var date1 = date2 = date3 = timestamp = hours = minutes = seconds = '';
date1 = date.split(':');
date2 = date1[0].split(' ');
date3 = date2[0].split('-'); // Change it based on your format
if( date1.length == 1 && date2.length == 1 ){
hours = '00';
minutes = '00';
seconds = '00';
}else{
hours = parseInt(date2[1]);
minutes = parseInt(date1[1]);
seconds = parseInt(date1[2]);
}
timestamp = new Date(parseInt(date3[0]), parseInt(date3[1])-1, parseInt(date3[2]), hours, minutes, seconds);
return timestamp;
}
});
Now, You may use this filter wherever the date format you want, and you may change the params as you like.
{{ '2016-07-07 05:27:30' | mysqlDateFormatToTimestamp | date:'LLLL dd, yyyy HH:mm:ss'}}
// results would comes like "July 07, 2016 05:27:30"
{{ '2016-07-07 05:27:30' | mysqlDateFormatToTimestamp | date:'yyyy'}}
// results would comes like "2016"

Resources