Converting IST to local time in angular js - angularjs

From server I am getting time in this format "21/11/2017 17:01:30", and this time is in IST. I want to convert this time to the users local time.
I am using below given code for that,
var startDateTimeArray = eachExeRun.startDate.split(" ");
var startDateArray = startDateTimeArray[0].split("/");
var startDate = new Date(startDateArray[2]+"-"+startDateArray[1]+"-"+startDateArray[0]+' '+startDateTimeArray[1]);
And now my startDate is "Tue Nov 21 2017 16:59:29 GMT+0530 (India Standard Time)"
In html I used like this
{{startDate | date:'yyyy-MM-dd HH:mm:ss'}}
After this to test my code I changed my system's timezone to pasific time zone, then my startTime changed to "Tue Nov 21 2017 16:59:29 GMT-0800 (Pacific Standard Time)", but in my view still its showing "2017-11-21 16:59:29".
How can I display updated time without using timezone in date filter(date:'yyyy-MM-dd HH:mm:ss Z').

Using moment.js is the beat way.
However, you could also write a custom filter for converting the dates.
Try this:
app.filter('myFormat', function() {
return function(x) {
var startDateTimeArray = x.split(" ");
var startDateArray = startDateTimeArray[0].split("/");
var startDate = new Date(startDateArray[2]+"-"+startDateArray[1]+"-"+startDateArray[0]+' '+startDateTimeArray[1]);
console.log(startDate);
//from timezone
var IST_timezone_offset = -330; // IST timezone offset -always known
var req_UTC_Milliseconds = (IST_timezone_offset * 60000) ;
//to timezone
var local_timezone_offset = startDate.getTimezoneOffset();
var local_UTC_Milliseconds = (local_timezone_offset * 60000);
var final_date = new Date( startDate.getTime() + (req_UTC_Milliseconds - local_UTC_Milliseconds ) );
return final_date;
};
});
Working Fiddle

Using momentJs it is quite simple:
Find the working code snippet below:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
<body>
<h2>My IST to Local System Date Convertor</h2>
<div ng-app="myApp" ng-controller="dateCtrl">
<p>{{convertIstToSystemLocalDateUsingTimeZone(IstStartDate)}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('dateCtrl', function ($scope) {
$scope.IstStartDate = '21/11/2017 17:01:30';
$scope.convertIstToSystemLocalDateUsingTimeZone = function (incomingISTString) {
return moment.tz(incomingISTString, 'DD-MM-YYYY HH:mm:ss', 'Asia/Kolkata')
.local().format('DD-MM-YYYY HH:mm:ss');
}
});
</script>
</body>
</html>

Related

Diffrence between two datetime in desire format using angular js

How to check diffrence between two datetime in desire format using angular js.
var ms = moment($scope.date1,"yyyy-MM-dd HH:mm:ss").diff(moment($scope.date2,"YYYY-MM-DD HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log("Date diff.........",s);
output:
date1........ 2017-12-26 16:20:00
date2........ 2017-12-26 15:10:38
Diff- 01:10
(If should ignore date because there is not date diffrence and if date diffrence is there then it show display like 03:10:05)
Diff (In format- DD-HH-MM)
DD-Days
HH-Hours
MM-Minutes
Tried Code:
$scope.cdate = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss');
console.log("current time........",$scope.cdate);
$scope.Mydata=Data.timestamp; //I am Getting this data from response
this.getDateDiff = function(cdate, Mydata) {
let d1 = new Date($scope.cdate);
let d2 = new Date($scope.Mydata);
let diff = Math.abs(d1.getTime() - d2.getTime());
let diffDate = new Date(0, 0, 0);
diffDate.setMilliseconds(diff);
let dayMills = ((60**2) * 24) * 1000;
let days = Math.round(diff / dayMills);
function formatNumberString(number) {
return ('0' + number).slice(-2);
}
return {
days: formatNumberString(days),
hours: formatNumberString(diffDate.getHours()),
minutes: formatNumberString(diffDate.getMinutes()),
seconds: formatNumberString(diffDate.getSeconds())
}
}
$scope.dateDiff = this.getDateDiff($scope.cdate, $scope.Mydata);
console.log("days diff.........",$scope.dateDiff);
Output:
Input:
current time- 2017-12-29 10:19:41
Mydata- 2017-02-09 18:16:38
result is coming wrong-
{days: "23", hours: "16", minutes: "03", seconds: "03"}
You can achieve it by using native JavaScript.
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.date1 = "2017-12-26 16:20:00";
$scope.date2 = "2017-12-26 15:10:38"
this.getDateDiff = function(date1, date2) {
let d1 = new Date(date1);
let d2 = new Date(date2);
let diff = Math.abs(d1.getTime() - d2.getTime());
let diffDate = new Date(0, 0, 0);
diffDate.setMilliseconds(diff);
let dayMills = ((60**2) * 24) * 1000;
let days = Math.round(diff / dayMills);
function formatNumberString(number) {
return ('0' + number).slice(-2);
}
return {
days: formatNumberString(days),
hours: formatNumberString(diffDate.getHours()),
minutes: formatNumberString(diffDate.getMinutes()),
seconds: formatNumberString(diffDate.getSeconds())
}
}
$scope.dateDiff = this.getDateDiff($scope.date1, $scope.date2);
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
</head>
<body ng-controller="MainCtrl">
<div>date1...... {{date1}}</div>
<div>date2...... {{date2}}</div>
<div>
<span>Diff - </span>
<span ng-if="dateDiff.days > 0">{{dateDiff.days}} : </span>
<span>{{ dateDiff.hours }} : </span>
<span>{{ dateDiff.minutes }}</span>
</div>
</body>
</html>
See if this works for you.
your controller file-
$scope.date1 = "2017-12-26 16:20:00";
$scope.date2 = "2017-12-26 15:10:38";
var diff = moment.utc(date1, "yyyy-MM-DD HH:mm:ss").diff(moment.utc(date2, "yyyy-MM-DD HH:mm:ss"), 'minutes');
var days=diff/(24*60);
var hours=diff/60;
var minutes=diff%60;
$scope.arr = [];
if(parseInt(days)){
arr.push(parseInt(days));
}
if(parseInt(hours)){
arr.push(('0'+hours).substring(-1, 2));
}
if(minutes){
arr.push(('0'+minutes).substring(-1, 2));
}
console.log(arr.join(':'));
Your html file-
...
<div>{{arr.join(':')}}</div>
...

angular material date picker field value empty

I want to get date of birth of a user, with predefined min and max date which is working fine.
And the date format i want is DD-MM-YYYY, for this i have defined following in config;
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
}}]);
and the controller has
$scope.user = {};
$scope.user.dob = new Date();
$scope.maxDate = new Date(
$scope.user.dob.getFullYear() - 10,
$scope.user.dob.getMonth(),
$scope.user.dob.getDate()
);
$scope.minDate = new Date(
$scope.user.dob.getFullYear() - 120,
$scope.user.dob.getMonth(),
$scope.user.dob.getDate()
);
and the HTML is;
<md-datepicker
ng-model="user.dob"
md-placeholder="Enter date of birth"
md-min-date="minDate"
md-max-date="maxDate">
</md-datepicker>
with this code the field shows current date by default, which i don't want,
i want the date field to be empty by default.
Also i want to get values in both ways as follows
1) date-month-year
And
2) date-month-year hour-minutes-seconds
When i tried to get the value it shows this "09-11-2016T18:30:00.000Z"
i want either "09-11-2016" or "09-11-2016 18:30:00"
Your mdDateLocaleProvider doesnt check for null values.
Your Problem is:
app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
$mdDateLocaleProvider.formatDate = function(date) {
return moment(date).format('DD-MM-YYYY');
}}]);
it needs to be something like:
$mdDateLocaleProvider.formatDate = function(date) {
var m = moment(date);
return m.isValid()? m.format('DD-MM-YYYY') : '';
};
Then you can set
$scope.user.dob=null;
And get an empty Datepicker.
The problem is your ng-model. You're initializing it with the current date:
$scope.user.dob = new Date();
Simply empty this variable and you'll be good ;)

Ionic Timezone Picker

I'm trying to implement a Timezone picker in my Ionic project and I'm running into some issues. And to be a bit more specific, the timezone picker will be used on the edit profile page for a user. This timezone is important because my application allows the user to checkin (like Untappd) an item that they are currently trying. And I want the checkin date to match their timezone.
Where I'm stuck: I'm getting a bit confused due to the assortment of libraries offered. And I haven't had any luck implementing the solutions that I've found. I'm also a bit new to working with timezones to this degree, so another question is, should I allow the user to change their GMT offset? Or is it common to now just auto-detect this?
I've run across the following libraries, but as mentioned above I haven't had any luck implementing these in my Angular/Ionic project. (See below for code snippets.)
Libraries found:
timezone-js
angular-tz-extensions
tzdata-javascript.org
moment-timezone
My implementation:
index.html (I realize that this is overkill, but was trying to get any of them to work.)
<!-- moment/timezone -->
<script src="lib/timezone-js/src/date.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.js"></script>
<script src="lib/angular-tz-extensions/lib/angular-tz-extensions.min.js"></script>
<script src="lib/moment/min/moment.min.js"></script>
<script src="lib/angular-moment/angular-moment.min.js"></script>
<script src="lib/moment-timezone/moment-timezone.js"></script>
<script src="lib/moment-timezone/moment-timezone-utils.js"></script>
app.js
angular.module('curdcollective', [
'ionic',
'ionic.service.core',
'ionic.service.deploy',
'ionic.service.analytics',
'ionic.service.push',
'ngIOS9UIWebViewPatch',
[...](Removed for brevity),
'Timezones'
])
.constant(
'$timezones.definitions.location',
'/lib/angular-tz-extensions/tz/data'
)
I don't understand how $timezones is available, but that's what the docs say.
profile_edit.html (This is what I'm trying to get to.)
<label class="item item-input item-select">
<div class="input-label">Timezone</div>
<select name="data[User][timezone]" ng-model="item.User.timezone">
<option ng-repeat="zone in zones by zone.name" ng-value="zone.abbr">{{zone}}</option>
</select>
</label>
<label class="item item-input item-select">
<div class="input-label">GMT Offset</div>
<select name="data[User][gmt_offset]" ng-model="item.User.gmt_offset">
<option ng-repeat="offset in offsets" ng-value="offset">{{offset}}</option>
</select>
</label>
controllers.js
/**
* ProfileController
* Methods related to the user profile.
*/
.controller('ProfileController', function($state, $scope, $ionicHistory, $ionicPopup, $timezones, angularMomentConfig, $ionicModal, $stateParams, $resource, $sanitize, AuthService, LoadingService, ApiService, Me, $cordovaSocialSharing, BucketService) {
//Resolve a timezone
// var scope.timezone = $timezone.resolve('America/New_York', new Date());
// console.log(scope.timezone);
//Apply the timezone when a new one is selected
//from the edit profile view.
this.applyTimezone = function ($timezone) {
angularMomentConfig.preprocess = 'utc';
angularMomentConfig.timezone = $timezone.getName();
console.log(angularMomentConfig.timezone);
};
//#url https://github.com/chouseknecht/angular-tz-extensions
$timezones.getZoneList($scope);
$scope.$on('zonesReady', function(zones){
$scope.zones = zones;
console.log($scope.zones);
});
[...](Removed code for brevity.)
$scope.getTimeZonesList = function(moment){
console.log('getTimeZonesList');
var rZones = angular.forEach(moment.tz.zones(), function (zone) {
return {
name: zone.displayName,
abbr: moment.tz(zone.displayName).zoneAbbr()
};
});
console.log(rZones);
return rZones;
};
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/profile_edit.html', {
scope: $scope
}).then(function(modal) {
$scope.editModal = modal;
});
//
$scope.showEditProfile = function(){
$scope.editModal.show();
};
$scope.hideEditProfile = function(){
$scope.editModal.hide();
};
})
I ended up making the following Angular Timezone service. It's not perfect and it could use some optimization and I could still use suggestions on how to make it better.
I'm auto-detecting if the user hasn't already set a timezone using Timezone.detect().
Here's the actual select code:
<select name="data[User][timezone]" ng-model="item.User.timezone" ng-options="zone.name for zone in zones" selected="item.User.timezone">
<option value="">Select Timezone</option>
</select>
See the gist at https://gist.github.com/robksawyer/98df7bb13d5efeac5dde.
/**
* Bower dependencies:
* timezone-js
* moment
* moment-timezone
* angular-moment
* angular-tz-extensions
*
* index.html:
* <script src="lib/timezone-js/src/date.js"></script>
* <script src="http://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.js"></script>
* <script src="lib/moment/min/moment-with-locales.min.js"></script>
* <script src="lib/moment-timezone/builds/moment-timezone-with-data.min.js"></script>
* <script src="lib/moment-timezone/moment-timezone-utils.js"></script>
* <script src="lib/angular-moment/angular-moment.min.js"></script>
* <script src="lib/angular-tz-extensions/lib/angular-tz-extensions.min.js"></script>
*/
angular.module('curdcollective.services', [
'angularMoment', 'Timezones'
])
/**
* TimezoneService
* Helper for Timezone related things
* #url https://github.com/chouseknecht/angular-tz-extensions
* #url https://github.com/urish/angular-moment
* #url http://momentjs.com/timezone/
*/
.service('TimezoneService', function(moment, $timezones, $filter, angularMomentConfig) {
//Get a list of timezones (via moment-timezone)
var timezones = [];
var autoDetectedTimezone = $timezones.getLocal() || 'UTC';
function pad(value) {
return value < 10 ? '0' + value : value;
}
function setDefaults(timezone){
if(!this.autoDetectedTimezone && !timezone){
return 'You need to detect the timezone first.';
}
//Set the default timezone
moment.tz.setDefault(this.autoDetectedTimezone);
angularMomentConfig.timezone = this.autoDetectedTimezone;
}
return {
//
//Initializes the timezone methods and loads required variables
//
initTimezones: function(){
this.timezones = [];
angular.forEach(moment.tz.names(), function (zone, key) {
this.push({
name: zone,
abbr: moment.tz(zone).zoneAbbr(),
offset: moment.tz(zone).format('Z')
});
}, this.timezones);
},
getTimezoneOffset: function(tz){
if(!tz){
tz = this.autoDetectedTimezone;
}
var rightNow = new Date();
var tzAlign = $timezones.align(rightNow, tz);
return tzAlign.getTimezoneOffset();
},
getHours: function(tz){
if(!tz){
tz = this.autoDetectedTimezone;
}
var rightNow = new Date();
var tzAlign = $timezones.align(rightNow, tz);
return tzAlign.getHours();
},
getGMTOffset: function(tz){
if(!tz){
tz = this.autoDetectedTimezone;
}
var rightNow = new Date();
var tzAlign = $timezones.align(rightNow, tz);
return $filter('date')(tzAlign,'Z');
},
//See https://github.com/chouseknecht/angular-tz-extensions
getLocale: function(tz){
if(!tz){
tz = this.autoDetectedTimezone;
}
return tz.locality;
},
//Handles setting the default timezone for the app.
setDefaults: function(timezone){
if(!this.autoDetectedTimezone && !timezone){
return 'You need to detect the timezone first.';
}
//Set the default timezone
moment.tz.setDefault(this.autoDetectedTimezone);
angularMomentConfig.timezone = this.autoDetectedTimezone;
},
//Handles auto-detecting the user's timezone
detect: function(){
this.autoDetectedTimezone = $timezones.getLocal() || 'UTC';
setDefaults(this.autoDetectedTimezone.name);
return this.autoDetectedTimezone.name;
},
//Retrieves a list of all timezones known
getTimezones: function(){
return this.timezones;
},
//DEPRECATED
/*createOffset: function(date) {
var sign = (date.getTimezoneOffset() > 0) ? '-' : '+';
var offset = Math.abs(date.getTimezoneOffset());
var hours = pad(Math.floor(offset / 60));
var minutes = pad(offset % 60);
return sign + hours + ':' + minutes;
}*/
};
});

Convert birthday to age in angularjs

I want to display age of all my users to grid. I am reading data from facebook.I am not storing it at anywhere.
i am displaying date like :
{{ friend.birthday }}
How can i display age instead of displaying birthday.
if it is possible to create filters than how to create filter and how to apply it.
You can implement a function:
Controller:
$scope.calculateAge = function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
HTML
{{ calculateAge(friend.birthday) }}
Or a filter:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
return function(birthdate) {
return calculateAge(birthdate);
};
});
HTML
{{ friend.birthday | ageFilter }}
Age algorithm taken from this SO answer.
[EDIT] If the age is less than 1 year, and you want to show months, you can modify the ageFilter to calculate the month difference:
app.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
function monthDiff(d1, d2) {
if (d1 < d2){
var months = d2.getMonth() - d1.getMonth();
return months <= 0 ? 0 : months;
}
return 0;
}
return function(birthdate) {
var age = calculateAge(birthdate);
if (age == 0)
return monthDiff(birthdate, new Date()) + ' months';
return age;
};
});
Demo Plunker - Age Function
Demo Plunker - Age Filter
Demo Plunker - Age Filter with Months < 1 year
If you're value is just for example "05/01/2016". This will be a useful code to convert the date to birthday.
AngularJS
app.filter('ageFilter', function(){
return function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
});
HTML
{{ relationTypePreDefined.birthdate | ageFilter }}
By the way I used this solution to convert a date coming from a jquery datepicker input to age.
If you are using momentjs. Then you can create filter simply by using this snippet
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
Idk why I can never reply to people, says I need more rep but to rep I need to comment.. whatever.
In response to #Dean Christian Armada's, I kept getting an error regarding the filter. But changing to the following seems to work fine so I do appreciate it!
$scope.getAge = function(birthday){
var birthday = new Date(birthday);
var today = new Date();
var age = ((today - birthday) / (31557600000));
var age = Math.floor( age );
return age;
}
And for the HMTL
{{ getAge(birthdate) }}

ngRepeat dont refresh when I change the values - AngularJS

I'm doing a application to a calendar and I create a function that everytime change the values of my variable called "$scope.days", when I was using the version 1.0 didnt give error, but now the ngRepeat doesnt refresh, the new values go to the variable, but the ngRepeat dont show the new result...
$scope.loadMonth = function()
{
$scope.titleCalendar = $scope.months[$scope.month-1].name + ' ' + $scope.year;
getTotalFebruary($scope.year);
var dtString = $scope.year + '/' + $scope.month + '/' + 1,
date = new Date(dtString),
day = 1,
weekday = date.getDay(),
totalDays = $scope.months[date.getMonth()].qty + date.getDay();
$scope.days = [];
for(var i = 0; i < totalDays; i++)
{
if(i < weekday)
$scope.days.push('');
else
$scope.days.push(day++);
}
};
my html:
<div class="day" ng-repeat="day in days"><p>{{ day }}</p></div>
If I put an alert after push new values, I can see the new values, but my ngRepeat doesnt refresh the results, I already try many things but didnt work. Somebody know the solution?
Not sure I understand what you are trying to achieve given the small sample of code you provided but if you look at this sample you'll see that it should update the display every time you click the click me text, just enter either 1,2, or 3 in the input area. you might want to check that looping logic of yours.
<html lang="en-US" ng-app="mainModule">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
</head>
<body>
<div ng-controller="mainController">
<input type="text" ng-model="monthModel" placeholder="enter 1 2 or 3"/>
<h1 ng-click="loadMonth(monthModel)">Click Me to Repeat</h1>
<span class="day" ng-repeat="day in days">{{ day }} , </span>
</div>
<script type="text/javascript">
var app = angular.module("mainModule", []);
app.controller("mainController", function ($scope) {
//$scope.monthModel = 1; // default some date
$scope.year = "2014";
$scope.months = [
{"name":"January", "qty":10},
{"name":"February", "qty":5},
{"name":"March", "qty":10},
];
$scope.loadMonth = function(monthModel)
{
$scope.month = monthModel;
$scope.titleCalendar = $scope.months[$scope.month-1].name + ' ' + $scope.year;
//getTotalFebruary($scope.year);
var dtString = $scope.year + '/' + $scope.month + '/' + 1,
date = new Date(dtString),
day = 1,
weekday = date.getDay(),
totalDays = $scope.months[date.getMonth()].qty + date.getDay();
$scope.days = [];
for(var i = 0; i < totalDays; i++)
{
//if(i < weekday)
// $scope.days.push('');
//else
$scope.days.push(day++);
console.log($scope.days) ;
}
};
});
</script>
</body>
</html>

Resources