how to display Json Formated Datetime in angularJs - 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');

Related

How to get specific month on 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");
}

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

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....
}

Formatting and displaying date in angularjs

I created a datepicker directive which uses a jquery datepicker to generate calender.We can format the way it displays the data after selecting a date. I have some date which is stored in the database.
My requirement is to load the date in some specific format only when it displaying and don't want to change the model data.
I created a filter to format the text but it often returns "Nan Undefined NaN"
This is my filter
myUploadApp.filter('cmdate', ['$filter', function ($filter) {
return function (input, format) {
if (input) {
return $filter('date')(new Date(Date.parse(input)), format);
} else {
return null;
}
};
}]);
And to invoke this filter " cmdate :'dd MMM yyyy' " this is added.My input date format will be like this "23/04/2016".
You should checkout moment.js - http://momentjs.com/
I use it to turn dates like this "2016-05-12T14:00:00.346Z" to words like "in 10 hours"
fromNow.filter.js:
myapp.filter('fromNow', [, function () {
return function (date) {
return moment(date).fromNow();
}
};
}]);
Check out to see if it has the formatter you require
Date.parse accepts string format MM/dd/yyyy, and your input likes dd/MM/yyyy, That's why it does not worked.
If you insist to use this format, need to correct the format before parse;
.filter('cmdate', ['$filter', function ($filter) {
return function (input, format) {
//swap month and date first
input = input.split('/');
input[0] = input.splice(1, 1, input[0])[0];
input = input.join('/');
var date = new Date(Date.parse(input));
if (input) {
return $filter('date')(new Date(Date.parse(input)), format);
} else {
return null;
}
};
}])

angular ui-grid : how to use a variable parameter in the field property

In my ui-grid, I need to bring the value given by the function of my personModel:
{field:'getValue("weight")',displayName:'Weight'},
But, I need to pass an other variable parameter to this function regarding to a date like this :
$scope.myDate=new Date();
{field:'getValue("weight",myDate)',displayName:'Weight'},
How can I achieve it ?
I would dynamically add this field to my data array after loading the data.
{field:'weightByDate', displayName:'Weight'},
and then
$scope.myDate=new Date();
$q.all([
myDataLoaderFunction.$promise
])
.then(function (data) {
for (var i = 0; i < data[0].length; i++) {
data[0][i]['weightByDate'] = $scope.getValue('weight', myDate);
}
$scope.gridOptions.data = data[0];
}, function () {
$scope.gridOptions.data = [];
});
Perhaps that would work for you? (Note I have not run this code, there might be a syntax error in there somewhere.)

Resources