How can I convert /Date(1422815400000)/ to a proper date format?
This is the code of the controller.js file which return data
for (i = 0; i < emp1.data.length; i++) {
if (date == emp1.data[i].Date) {
if (emp1.data[i].InOut == 'I') {
temp = temp + " In : " + emp1.data[i].Time;
}
else {
temp = temp + " Out : " + emp1.data[i].Time;
}
}
else {
var newDate = Date.parse((emp1.data[i - 1].Date).toString());
modifyArray.push({
"EmployeeName": emp1.data[i - 1].EmployeeName, "Date": emp1.data[i - 1].Date,
"InOut": temp, "Hours": emp1.data[i - 1].Hours
});
temp = "";
date = emp1.data[i].Date;
}
}
$scope.EmployeesData = modifyArray;
There's a special date filter in AngularJS to change for displaying dates.
In HTML Template Binding
{{ date_expression | date : format : timezone}}
In JavaScript
$filter('date')(date, format, timezone)
See https://docs.angularjs.org/api/ng/filter/date
What you are getting is a Unix timestamp, you can make a normal date of it using
var date = new Date(timestamp)
in your case:
var date = new Date(1422815400000)
Related
There are 7 input fields in my code but I want to use them for only one. Also there are multiple pages where this datepicker is used all done through a common datepicker directive. I don't want the other pages and input fields to get affected with this change. Here is my code :
beforeShowDay: function(date) {
var month = date.getMonth() + 1;
var year = date.getFullYear();
var day = date.getDate();
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = '0' + month;
}
var newDate = month + "/" + day + "/" + year;
if (jQuery.inArray(newDate, highlight_date) != -1) {
//console.log(newDate);
return [true, "highlight"];
}
return [true];
}
I am trying to push mixpanel data into a single Google Sheet using code from here:
https://github.com/melissaguyre/mixpanel-segmentation-google-spreadsheets
I am having issues with the API_PARAMETERS not looping through as expected. (Formula, Formula1, & Formula2) The first two parameters loop through fine, but when the final is added, I get the error:
TypeError: Cannot read property "2016-07-11" from undefined. (line 143, file "Code")
Here is the code:
* Step 1) Fill in your account's Mixpanel Information here
`enter code here`*/
var API_KEY = '******';
var API_SECRET = '****';
/**
* Step 2) Define the tab # at which to create new sheets in the spreadsheet.
* 0 creates a new sheet as the first sheet.
* 1 creates a new sheet at the second sheet and so forth.
*/
var CREATE_NEW_SHEETS_AT = 0;
/**
* Step 3) Define date range as a string in format of 'yyyy-mm-dd' or '2013-09-13'
*
* Today's Date: set equal to getMixpanelDateToday()
* Yesterday's Date: set equal to getMixpanelDateYesterday()
*/
var FROM_DATE = getMixpanelDate(7);
var TO_DATE = getMixpanelDate(1);
/**
* Step 4) Define Segmentation Queries - Get data for an event, segmented and filtered by properties.
var API_PARAMETERS = {
'Formula' : [ 'QuestionAsked', '(properties["InputMethod"]) == "Voice" or (properties["InputMethod"]) == "Text" ', 'general', 'day', 'B7'],
'Formula1' : [ 'QuestionAsked', '(properties["InputMethod"]) == "Voice" or (properties["InputMethod"]) == "Text" ', 'unique', 'day', 'B2'],
//'Formula2' : [ 'QuestionAnswered', '(properties["InputMethod"]) == "Voice" or (properties["InputMethod"]) == "Text" ', 'unique', 'day', 'B3' ],
};
// Iterates through the hash map of queries, gets the data, writes it to spreadsheet
function getMixpanelData() {
for (var i in API_PARAMETERS)
{
var cell = API_PARAMETERS[i][4];
fetchMixpanelData(i, cell);
}
}
// Creates a menu in spreadsheet for easy user access to above function
function onOpen() {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
activeSpreadsheet.addMenu(
"Mixpanel", [{
name: "Get Mixpanel Data", functionName: "getMixpanelData"
}]);
}
/**
* Gets data from mixpanel api and inserts to spreadsheet
*
*/
function fetchMixpanelData(sheetName, cell) {
var c = cell;
var expires = getApiExpirationTime();
var urlParams = getApiParameters(expires, sheetName).join('&')
+ "&sig=" + getApiSignature(expires, sheetName);
// Add URL Encoding for special characters which might generate 'Invalid argument' errors.
// Modulus should always be encoded first due to the % sign.
urlParams = urlParams.replace(/\%/g, '%25');
urlParams = urlParams.replace(/\s/g, '%20');
urlParams = urlParams.replace(/\[/g, '%5B');
urlParams = urlParams.replace(/\]/g, '%5D');
urlParams = urlParams.replace(/\"/g, '%22');
urlParams = urlParams.replace(/\(/g, '%28');
urlParams = urlParams.replace(/\)/g, '%29');
urlParams = urlParams.replace(/\>/g, '%3E');
urlParams = urlParams.replace(/\</g, '%3C');
urlParams = urlParams.replace(/\-/g, '%2D');
urlParams = urlParams.replace(/\+/g, '%2B');
urlParams = urlParams.replace(/\//g, '%2F');
var url = "http://mixpanel.com/api/2.0/segmentation?" + urlParams;
Logger.log("THE URL " + url);
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var dataAll = JSON.parse(json);
var dates = dataAll.data.series;
Logger.log(API_PARAMETERS);
for (i in API_PARAMETERS){
var parametersEntry = API_PARAMETERS[i];
for (i in dates){
data = dataAll.data.values[parametersEntry[0]][dates[i]];
}
insertSheet(data, c);
};
}
function insertSheet(value, cell) {
var sheetName = 'Formula';
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetName);
var c = sheet.getRange(cell).setValue(value);
};
/**
* Returns an array of query parameters
*/
function getApiParameters(expires, sheetName) {
var parametersEntry = API_PARAMETERS[sheetName];
return [
'api_key=' + API_KEY,
'expire=' + expires,
'event=' + parametersEntry[0],
'where=' + parametersEntry[1],
'type=' + parametersEntry[2],
'unit=' + parametersEntry[3],
'from_date=' + FROM_DATE,
'to_date=' + TO_DATE
];
}
/**
* Sorts provided array of parameters
*
function sortApiParameters(parameters) {
var sortedParameters = parameters.sort();
// Logger.log("sortApiParameters() " + sortedParameters);
return sortedParameters;
}
/**
function getApiExpirationTime() {
var expiration = Date.now() + 10 * 60 * 1000;
// Logger.log("getApiExpirationTime() " + expiration);
return expiration;
}
/**
* Returns API Signature calculated using api_secret.
*/
function getApiSignature(expires, sheetName) {
var parameters = getApiParameters(expires, sheetName);
var sortedParameters = sortApiParameters(parameters).join('') + API_SECRET;
// Logger.log("Sorted Parameters " + sortedParameters);
var digest = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, sortedParameters);
var signature = '';
for (j = 0; j < digest.length; j++) {
var hashVal = digest[j];
if (hashVal < 0) hashVal += 256;
if (hashVal.toString(16).length == 1) signature += "0";
signature += hashVal.toString(16);
}
return signature;
}
/**
*********************************************************************************
* Date helpers
*********************************************************************************
*/
// Returns today's date string in Mixpanel date format '2013-09-11'
function getMixpanelDateToday() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if ( mm < 10 ) {
mm = '0' + mm;
}
today = yyyy + '-' + mm + '-' + dd;
return today;
}
// Returns yesterday's's date string in Mixpanel date format '2013-09-11'
function getMixpanelDate(days){
var today = new Date();
var d = new Date(today);
d.setDate(today.getDate() - days);
//Logger.log(yesterday);
var dd = d.getDate();
//Logger.log(yesterday);
var mm = d.getMonth() + 1;
var yyyy = d.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
d = yyyy + '-' + mm + '-' + dd;
//Logger.log(yesterday);
return d;
}
Can anyone explain why the Datepicker expects value to be date object as per the official example?
https://material.angularjs.org/latest/demo/datepicker
To be honest this is a pain because before binding server response to the form I have to determine if a field is data type and convert the value:
$scope.myDate = new Date('2015-01-11');
Is there any way I could simply populate datepicker with a string value?
$scope.myDate = '2015-01-11';
The problem with a string value would be parsing. May 10, 2016 and October 5, 2016 could be confused. 2016-05-10 or 2016-10-05. The date object protects against that. Can you not use a defined filter to convert your string data to a date object?
I quickly modified some code below from a Date Filter I have for Angular 1.x, which uses a numeric date format of YYYYMMDD (20160516).
/**
* #name yourDate
* #ngdoc filter
* #requires $filter
* #param DateValue {string} Date Value (YYYY-MM-DD)
* #returns Date Filter with the Date Object
* #description
* Convert date from the format YYYY-MM-DD to the proper date object for future use by other objects/filters
*/
angular.module('myApp').filter('yourDate', function($filter) {
var DateFilter = $filter('date');
return function(DateValue) {
var Input = "";
var ResultData = DateValue;
if ( ! ( (DateValue === null) || ( typeof DateValue == 'undefined') ) ) {
if ( Input.length == 10) {
var Year = parseInt(Input.substr(0,4));
var Month = parseInt(Input.substr(5,2)) - 1;
var Day = parseInt(Input.substr(8, 2));
var DateObject = new Date(Year, Month, Day);
ResultData = DateFilter(DateObject); // Return Input to the original filter (date)
} else {
}
} else {
}
return ResultData;
};
}
);
/**
* #description
* Work with dates to convert from and to the YYYY-MM-DD format that is stored in the system.
*/
angular.module('myApp').directive('yourDate',
function($filter) {
return {
restrict: 'A',
require: '^ngModel',
link: function($scope, element, attrs, ngModelControl) {
var slsDateFilter = $filter('yourDate');
ngModelControl.$formatters.push(function(value) {
return slsDateFilter(value);
});
ngModelControl.$parsers.push(function(value) {
var DateObject = new Date(value); // Convert from Date to YYYY-MM-DD
return DateObject.getFullYear().toString() + '-' + DateObject.getMonth().toString() + '-' + DateObject.getDate().toString();
});
}
};
}
);
This code just uses the standard Angular Filter options, so you should then be able to combine this with your Material date picker.
I want to display age of all users in my meanjs app.
How can i display age instead of displaying birthdate. my plunk demo
Controller:
$scope.agedate = new Date();
$scope.calculateAge = function calculateAge(birthday) {
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Html:
<p ng-bind="items.user.displayName"></p>
<p ng-bind="items.user.dateofbirth | date"></p>
<p ng-bind="calculateAge(items.user.dateofbirth)"></p>
my data:-
$scope.items = {
"_id": "5733163d4fc4b31d0ff2cb07",
"user": {
"_id": "5732f3954fc4b31d0ff2cb05",
"displayName": "karthi keyan",
"dateofbirth": "1991-10-04T18:30:00.000Z",
"profileImageURL": "./modules/users/client/img/profile/uploads/ed948b7bcd1dea2d7086a92d27367170"
},
"__v": 0,
"comments": [],
"content": "this is testing purpose for e21designs",
"categoryone": "Moral Ethics",
"category": "Anonymous Question",
"title": "Worried",
"created": "2016-05-11T11:23:41.500Z",
"isCurrentUserOwner": true
};
My plunk demo
Your code almost does what you want.
It has a problem in dateofbirth property, because it's a string (according your example.
To display it as the date you're using date filter which handles this for you.
But, in your calculateAge function you need to convert your string into Date.
Try the following:
$scope.calculateAge = function calculateAge(birthday) { // birthday is a string
var ageDifMs = Date.now() - new Date(birthday).getTime(); // parse string to date
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Hope it will help.
Please note that this problem is completely unrelated to angularjs. It is pure Javascript date differences calculation.
I strongly suggest to use a third party library like (momentjs)[http://momentjs.com/] to make such calculation, and in order to help you parse the string formatted date.
Here is a simple function in javascript to calculate age for the date format "YYYY-MM-DD". Where the dateString parameter to the function is the birth date.
function calculateAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
You could use this as an angular function by applying $scope to it. Like this:
$scope.calculateAge = function(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
When I enter "31/12/2012" in my field (date format is MM/DD/YYYY), it changes the date to "7/12/2014" in the field. I would rather it error with a "not valid" error message.
I have inherited this code from a previous developer:
function dateRangeCheck(val, field) {
field.vtypeText = '';
var date = field.parseDate(val);
if (!date) {
field.vtypeText = val + ' is not a valid date - it must be in the format (MM/DD/YYYY).';
return false;
}
var retVal = true;
if (field.fromField) {
var fromField = Ext.getCmp(field.fromField);
var fromDate = fromField.parseDate(fromField.getValue());
// If we don't have a fromDate to validate with then return true
if (!fromDate)
return true;
retVal = (date >= fromDate);
if (retVal)
fromField.clearInvalid();
}
else if (field.toField) {
var toField = Ext.getCmp(field.toField);
var toDate = toField.parseDate(toField.getValue());
// If we don't have a toDate to validate with then return true
if (!toDate)
return true;
retVal = (date <= toDate);
if (retVal)
toField.clearInvalid();
}
if (!retVal) {
field.vtypeText = 'From Date must be less than or equal to To Date.';
}
return retVal;
}
When I try to use the default 'daterange' vtype, as soon as I type a "3" in the field, it throws a JS runtime exception 'object doesn't support this property or method'.
Note that you can set Date.useStrict = true globally and the DateField will use that by default.
For Ext 4+ it would be Ext.Date.useStrict = true instead.
It looks like your call to parseDate just needs to have the strict switch set.
strict (optional) True to validate date strings while parsing (i.e.
prevents javascript Date "rollover")(defaults to false). Invalid date
strings will return null when parsed.
> Date.parseDate('31/12/2012','m/d/Y')
Sat Jul 12 2014 00:00:00 GMT-0500 (Central Daylight Time)
> Date.parseDate('31/12/2012','m/d/Y', true)
null
The parseDate method in DateField is private and undocumented, and the discussion to allow strict date parsing in ExtJS 3.x never bore any fruit. I think your best bet is to use an override to allow strict date parsing.
// before you use your DateFields
Ext.override(Ext.form.DateField, {
safeParse : function(value, format) {
if (Date.formatContainsHourInfo(format)) {
// if parse format contains hour information, no DST adjustment is necessary
return Date.parseDate(value, format, this.strict);
} else {
// set time to 12 noon, then clear the time
var parsedDate = Date.parseDate(value + ' ' + this.initTime, format + ' ' + this.initTimeFormat, this.strict);
if (parsedDate) {
return parsedDate.clearTime();
}
}
}
});
//... and in your DateField config:
strict: true,