How to get specific month on AngularJS - angularjs

How can I get the specific date month coming from the backend on angularJS
I wish to add something like this:
var curMonth = new Date().getMonth();
var monthData = vm.paymentsData[0].date.Date().getMonth();
if (curMonth == monthData) {
console.log ("Same Month");
}
Im getting error on:
var monthData = vm.paymentsData[0].date.Date().getMonth();
it says:
angular.js:14328 TypeError: vm.paymentsData[0].date.Date is not a function
Thanks
Data from the backend

I think your code should be written as follows:
var curMonth = new Date().getMonth();
// this maybe a string .. and you cannot call Date() function in that way.
var monthData = vm.paymentsData[0].date;
// Date function should be called this way.
var monData = (new Date(monthData)).getMonth();
if (curMonth == monData) {
console.log ("Same Month");
}

Related

How to convert readable date time in timestamp which comes from backend

I want to convert the commit date and time to time stamp which I get from my APIs.
But I don't know how to do this in angular?
Here is my controller code :
var commitDate = item.commitMetaData.commitDate;
var dat = new Date(commitDate);
But it says "Invalid Date"
PS: Thanks in advance
What you could do is generate the date from the values montValue , year, dayOfMonth
with plain Javascript you could just do
var d = new Date();
d.setMonth(commitDate.monthValue +1); //see explanation below
d.setDate(commitDate.dayOfMonth);
d.setYear(commitDate.year);
be careful the months start at 0 so January is actually 0 so in your example you would have to add +1
You can also create a filter for this
.filter('createDate', function ($filter) {
return function (input) {
if (input != null && input != undefined) {
var d = new Date();
d.setMonth(input.monthValue +1); //see explanation below
d.setDate(input.dayOfMonth);
d.setYear(input.year);
return d;
}
};
})
and call it like
var commitDate = item.commitMetaData.commitDate;
var dat = $filter('createDate')(commitDate);
reference JS Date

how to display Json Formated Datetime in angularJs

how to display Json datetime formate in angularJs its showing Datetime as"/Date(820434600000)/"
Angular Code
app.controller("MyDeptCntrl", function ($scope, MyDeptSer) {
$scope.BtnDept = function () {
var Dept = MyDeptSer.GetDeptData();
Dept.then(function (d) {
$scope.DeptData = d.data;
// $filter('date')(date, format, timezone)
},function(e){
alert('Loading Failed....')
})
}
use below function to parse the date first
function dateParser(input){
input = input.replace('/Date(', '');
return new Date(parseInt(input,10));
}
so
$scope.DeptData = dateParser(d.data);
You can try this
convertJsonDateTimeToJs: function (jsonDate) {
var dateSlice = jsonDate.slice(6, 24);
var milliseconds = parseInt(dateSlice);
return new Date(milliseconds);
}
I'd recommend changing your server side code to use a friendlier JSON serializer but if not, try:
// You start with /Date(820434600000)/
// substr(6) takes off the /Date( part and pass the number 820434600000 into the parseInt function.
// Note: the parseInt function will ignore the )/ and the end.
var friendlyDate = new Date(parseInt($scope.DeptData.someDateMember.substr(6)));
// Then, you can format it using angular date filter -- for example:
$scope.formattedDate = $filter('date')(friendlyDate, 'MM/dd/yyyy');

Format Date in AngularJS coming from $http.get in large json data response

I am successfully calling $http.get in my Angular controller and getting back a large json object. Like this:
var self=this;
self.createNewStatusReport = function()
{
$http.get(self.NewStatusReportUrl).then(function(response)
{
self.AngularModel.StatusReportJsons.push(response.data);
});
};
The returned json includes many dates. The format, unfortunately, looks like this: /Date(1420099200000)/. Here's a simplified piece of the response data:
{
"StatusReportID": 25,
"DueDate": "/Date(1468566000000)/",
"SubmitDate": null,
"WorkStatement": [
{
"WorkStatementID": 41,
"Milestone": [
{
"MilestoneID": 501,
"ContractorComments": null,
"Title": "Do some specific piece of work",
"StartDate": "/Date(1459494000000)/",
"EndDate": "/Date(1469948400000)/",
"IsCompleted": false,
...
I also have (some) control over the server side, but can't change the date types in StatusReportJson from DateTime? to string. It is MVC written in C#:
[HttpGet]
public JsonResult NewStatusReport(string agreementNumber)
{
var statusReport = StatusReports.GetStatusReport(25);
return Json(new StatusReportJson(statusReport), JsonRequestBehavior.AllowGet);
}
Is there an easy way to recursively convert these date strings to date objects? The response data comes to me already parsed; can I insert my own parse step? On the server side, can I make the dates come in as date strings that look more like "2016-04-01T00:00:00" or simply "2016-04-01" without modifying my StatusReportJson object's data types? Others have already solved the conversion problem here: How do I format a Microsoft JSON date? I need help structuring where to put the solution so it is effective in my case. Thanks for helping!
Hope this solves your problem:
$scope.DateIssue = function(input) {
input = '/Date(1468566000000)/';
$scope.formatedDate = input.toString().replace('/Date(', '').replace(')/', '');
$scope.formatedDate = $filter('date', $scope.formatedDate);
return $scope.formatedDate
};
Here's how I solved this. First, I used the JavaScript serializer on the server side like this:
[HttpGet]
public JsonResult NewStatusReport(string agreementNumber)
{
var statusReport = StatusReports.GetStatusReport(25);
var statusReportJson = new StatusReportJson(statusReport);
var json = new JavaScriptSerializer().Serialize(statusReportJson);
return Json(json, JsonRequestBehavior.AllowGet);
}
Then, on the client side, I pulled in code from this excellent page http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html and called it like this:
var self = this;
$http.get(self.NewStatusReportUrl).then(function(response)
{
var jsonObject = jQuery.parseJSON(response.data, true);
self.AngularModel.StatusReportJsons.push(jsonObject);
});
Thanks to Robert Koritnik for the answer! And thanks to everyone who helped!
A little late, but I thought helpful.
Most of the suggestions were to locally convert it. In my case the date is returned as string (with Timezone info).
E.g. '2018-06-01T13:57:41.3867449Z'
So I created a common service for getJson & PostJson and in handled responses there with '$q'.
if (response.data) {
// Check for datetime object & convert
// TODO:: *** May impact performance, so check later or use momentJS
//console.info('Before-convertDateStringsToDates:', new Date());
appUtils.convertDateStringsToDates(response.data);
//console.info('After-convertDateStringsToDates:', new Date());
}
My appUtil method is as below:
// --------------------------------------------------------------------------------
// Ref: http://aboutcode.net/2013/07/27/json-date-parsing-angularjs.html
// Function to convert string (as ReGex format) property to date - used as generic in Common Serivce.
convertDateStringsToDates(input) {
// ReGex for format we receive from Web API e.g. "1980-05-09T00:00:00Z"
var jsonDateTimeFormatRegex = "((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))";
// Ignore things that aren't objects.
if (typeof input !== "object") return input;
for (var key in input) {
if (!input.hasOwnProperty(key)) continue;
var value = input[key];
var match;
// Check for string properties which look like dates.
// TODO: Improve this regex to better match ISO 8601 date strings.
if (typeof value === "string" && (match = value.match(jsonDateTimeFormatRegex))) {
// Assume that Date.parse can parse ISO 8601 strings, or has been shimmed in older browsers to do so.
//console.info(match[0]);
var date = new Date(match[0]); // Need to convert to UTC. Ref: https://stackoverflow.com/a/14006555/1161069
input[key] = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
// var milliseconds = Date.parse(match[0]);
// if (!isNaN(milliseconds)) {
// input[key] = new Date(milliseconds);
// }
} else if (typeof value === "object") {
// Recurse into object
this.convertDateStringsToDates(value);
}
}
}
Now, after each GET or POST request, I get my JSON with proper dates.
Just in case someone wants to know Web API code, it's as below:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
//var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
// other code ......
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
//jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
JsonSerializerSettings jSettings = new JsonSerializerSettings()
{
Formatting = Formatting.None
};
jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
jsonFormatter.SerializerSettings = jSettings;
// rest of the code....
}

Angularjs - Time difference between my data time and CURRENT TIME

I am trying to display the time difference between my {{trade.timer}} and the current time but coudn't succeed after many tries.
I am looking to make the $scope.gains[i].timer = vtime - "CURRENTTIME"
Here is my code:
$scope.updatetimerValue = function (timerValue){
$.each(timerValue, function(k, v) {
for (var i =0; i < $scope.gains.length ; i ++) {
if($scope.gains[i].orderid == v.orderid){
$scope.gains[i].timer = v.time;
}
}
});
}
<td>{{gain.timer | date: 'HH:mm'}}</td>
Any idea?
Note: v.time time format is yyyy-MM-dd HH:mm:ss
You can get date difference between two days with basic javascript.
var date = new Date('10/27/2014');
var currentDate = new Date();
var milisecondsDiff = date-currentDate;
var secondsDiff = miliseconds/1000;
var minutesDiff = seconds/60;
var hoursDiff = minutes/60;
var daysDiff = hours/24;
Also I suggest don't mix up AngularJS and JQuery.
And instead $.each use the angular.forEach
angular.forEach(values, function(value, key) {
///
});
or even better to use simple for loop, because it works faster.

Built a JSON from string pieces

I work with a line chart in ExtJS4 now. The chart is based on the data of the store. The store change its data with help 'loadRawData()' function.
Familiar situation, isn't it?
AJAX sends strings every 10 seconds and I need to built JSON from this pieces of strings. I'm trying:
success: function(response) {
var requestMassive = JSON.parse(response.responseText);
var jArray = [];
for(var i=0;i<requestMassive.length;i++){
var firstPiece = JSON.parse(response.responseText)[i].date;
var secondPiece = JSON.parse(response.responseText)[i].connectCount;
var recording = "{'machinesPlayed':"+firstPiece+", 'machinesOnline':"+secondPiece+"}";
jArray.push(recording);
}
jArray = '['+jArray+']';
store.loadRawData(jArray);
}
But it is wrong way. How to do it properly?
You could use loadData() function instead of loadRawData(). loadData() only needs an array of objects.
success: function(response) {
var requestMassive = JSON.parse(response.responseText);
var jArray = [];
for(var i=0;i<requestMassive.length;i++){
jArray.push({ machinesPlayed: requestMassive[i].date, machinesOnline: requestMassive[i].connectCount});
}
store.loadData(jArray);
}
I didnt get what you are trying to achieve.But it can be formed this way.Try this out.
var recording = {
"machinesPlayed" : firstPiece,
"machinesOnline" : secondPiece
}
jArray.push(recording);
OR
jArray.push({
"machinesPlayed" : firstPiece,
"machinesOnline" : secondPiece
});

Resources