How to set locale locally for moment.js - momentjs

The below code gives invalid date
moment.locale('en');
var localLocale = moment('enero 22, 2017', 'MMMM DD, YYYY');
localLocale.locale('es');
alert(localLocale.format('L'));'

You will need to import that particular locale js from Moment.js repo.
I've imported this in below code and this code works perfectly:
https://raw.githubusercontent.com/moment/moment/develop/locale/es.js
//! moment.js locale configuration
//! locale : Spanish [es]
//! author : Julio Napurí : https://github.com/julionc
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_');
var monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_');
var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i];
var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;
var es = moment.defineLocale('es', {
months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),
monthsShort : function (m, format) {
if (!m) {
return monthsShortDot;
} else if (/-MMM-/.test(format)) {
return monthsShort[m.month()];
} else {
return monthsShortDot[m.month()];
}
},
monthsRegex : monthsRegex,
monthsShortRegex : monthsRegex,
monthsStrictRegex : /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,
monthsShortStrictRegex : /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,
monthsParse : monthsParse,
longMonthsParse : monthsParse,
shortMonthsParse : monthsParse,
weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'),
weekdaysParseExact : true,
longDateFormat : {
LT : 'H:mm',
LTS : 'H:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D [de] MMMM [de] YYYY',
LLL : 'D [de] MMMM [de] YYYY H:mm',
LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm'
},
calendar : {
sameDay : function () {
return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
nextDay : function () {
return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
nextWeek : function () {
return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
lastDay : function () {
return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
lastWeek : function () {
return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
sameElse : 'L'
},
relativeTime : {
future : 'en %s',
past : 'hace %s',
s : 'unos segundos',
m : 'un minuto',
mm : '%d minutos',
h : 'una hora',
hh : '%d horas',
d : 'un día',
dd : '%d días',
M : 'un mes',
MM : '%d meses',
y : 'un año',
yy : '%d años'
},
dayOfMonthOrdinalParse : /\d{1,2}º/,
ordinal : '%dº',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
return es;
})));
Your Code:
moment.updateLocale('es');
var localLocale = moment('enero 22, 2017', 'MMMM DD, YYYY');
alert(localLocale.format('L'));
Demo:
http://jsfiddle.net/6df2xf80/

Related

How I can reduce the time of a for loop in Flutter?

I have a method called getNearByPlaces(), then I have for loop that iterates over each place_id, and send a request to google API, to get the name of the place_id,
so this operation takes around 15 seconds, how I can make it faster?
Future<void> getNearByPlaces(double latitude, double longitude) async {
List results = [];
List placesId = [];
List nearbyPlaces = [];
String nearbyUrl =
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${longitude}&radius=500&key=${mapKey}";
var nearbyResponse =
await RequestAssistant.getRequest(Uri.parse(nearbyUrl));
if (nearbyResponse == "Failed.") {
return;
}
results = nearbyResponse["results"];
for (int i = 0; i < results.length; i++) {
placesId.add(results[i]['place_id']);
String placeDetailsUrl =
"https://maps.googleapis.com/maps/api/place/details/json?place_id=${results[i]['place_id']}&key=$mapKey";
var response =
await RequestAssistant.getRequest(Uri.parse(placeDetailsUrl));
if (response == "Failed.") {
return;
}
if (response["status"] == "OK") {
await nearbyPlaces.add(response["result"]["name"]);
}
}
print(nearbyPlaces);
await FirebaseFirestore.instance
.collection("nearbyPlaces")
.doc(uid)
.set({'nearbyPlaces': nearbyPlaces});
}
If you just use only name in the detail result, you don't need to query again by 'place_id' because I found that there are more information in 'nearbysearch' API results.
For example, icon, name, photos and so on like below.
https://developers.google.com/maps/documentation/places/web-service/search
{
"html_attributions" : [],
"next_page_token" : "CpQCAgEAAFxg8o-eU7_uKn7Yqjana-HQIx1hr5BrT4zBaEko29ANsXtp9mrqN0yrKWhf-y2PUpHRLQb1GT-mtxNcXou8TwkXhi1Jbk-ReY7oulyuvKSQrw1lgJElggGlo0d6indiH1U-tDwquw4tU_UXoQ_sj8OBo8XBUuWjuuFShqmLMP-0W59Vr6CaXdLrF8M3wFR4dUUhSf5UC4QCLaOMVP92lyh0OdtF_m_9Dt7lz-Wniod9zDrHeDsz_by570K3jL1VuDKTl_U1cJ0mzz_zDHGfOUf7VU1kVIs1WnM9SGvnm8YZURLTtMLMWx8-doGUE56Af_VfKjGDYW361OOIj9GmkyCFtaoCmTMIr5kgyeUSnB-IEhDlzujVrV6O9Mt7N4DagR6RGhT3g1viYLS4kO5YindU6dm3GIof1Q",
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.867217,
"lng" : 151.195939
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png",
"name" : "Biaggio Cafe - Pyrmont",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 600,
"html_attributions" : [],
"photo_reference" : "CnRnAAAAmWmj0BqA0Jorm1_vjAvx1n6c7ZNBxyY-U9x99-oNyOxvMjDlo2npJzyIq7c3EK1YyoNXdMFDcRPzwLJtBzXAwCUFDGo_RtLRGBPJTA2CoerPdC5yvT2SjfDwH4bFf5MrznB0_YWa4Y2Qo7ABtAxgeBIQv46sGBwVNJQDI36Wd3PFYBoUTlVXa0wn-zRITjGp0zLEBh8oIBE",
"width" : 900
}
],
"place_id" : "ChIJIfBAsjeuEmsRdgu9Pl1Ps48",
"price_level" : 1,
"rating" : 3.4,
"reference" : "ChIJIfBAsjeuEmsRdgu9Pl1Ps48",
"types" : [ "cafe", "bar", "restaurant", "food", "establishment" ],
"vicinity" : "48 Pirrama Rd, Pyrmont"
},
So you just iterate 'nearbysearch' result and making 'nearbyPlaces' data.
...
results = nearbyResponse["results"];
for (int i = 0; i < results.length; i++) {
placesId.add(results[i]['place_id']);
nearbyPlaces.add(results[i]['name');
}
print(nearbyPlaces);
...

Firebase realtime database multi location update through cloud function transactions not working

I got a firebase realtime db (js sdk) where I count users for each location (groups/location/Items/{locationId}/usercount). I also have at a root level, a list of users where for each user I have a list of locations. Within each of these locations I have a counter that counts the total number of useres for that location (users/{userId}/groups/location/Items/{locationId}/usercount).
a) So whenever a user is added to to a location at groups/location/Items/{locationId}/users, the counter at groups/location/Items/{locationId}/usercount is incremented.
b) At the same time a counter at users/groups/location/Items/{locationId}/usercount is also incremented for each user that has this location in users/{userId}/groups/location/Items/.
Below you'll find the json data structure as well as the cloud function supposed to increment both counters (a and b). Part (a) of the function works perfectly. As for part (b) it only works for the user that was just added at groups/location/Items/{locationId}/users (user yjXidCKJuYZ71TNzYe9ob5Raaub2 as per hereby json) on not for ALL users at users/{userId}.
I need this function to increment all the counters of users within users/{userId} that have the location to which a user was added.
I hope I'm clear enough and would REALLY appreciate some help on this. Maybe I should not be using transactions.
Thanks a lot!
"groups" : {
"location" : {
"Items" : {
"NA" : {
"code" : "NA",
"created" : "2019-04-03--19:10:11",
"id" : "NA",
"label" : "North America",
"levelIndex" : 1,
"levelName" : "Continent",
"type" : "location",
"usercount" : 2,
"users" : {
"Xi6XiXdxDAWqvjmSUeobnhDTe4k2" : {
"created" : "2019-04-03--19:10:11",
"id" : "Xi6XiXdxDAWqvjmSUeobnhDTe4k2",
"ip" : "hidden",
"label" : "Anonymous"
},
"yjXidCKJuYZ71TNzYe9ob5Raaub2" : {
"created" : "2019-04-03--19:10:11",
"id" : "yjXidCKJuYZ71TNzYe9ob5Raaub2",
"ip" : "hidden",
"label" : "Anonymous"
}
}
}
}
}
},
"users" : {
"Xi6XiXdxDAWqvjmSUeobnhDTe4k2" : {
"created" : "2019-04-03--19:10:11",
"groups" : {
"location" : {
"Items" : {
"NA" : {
"code" : "NA",
"created" : "2019-04-03--19:10:11",
"id" : "NA",
"label" : "North America",
"levelIndex" : 1,
"levelName" : "Continent",
"type" : "location",
"usercount" : 1
}
}
}
},
"id" : "Xi6XiXdxDAWqvjmSUeobnhDTe4k2",
"ip" : "hidden",
"label" : "Anonymous"
},
"yjXidCKJuYZ71TNzYe9ob5Raaub2" : {
"created" : "2019-04-03--19:10:11",
"groups" : {
"location" : {
"Items" : {
"NA" : {
"code" : "NA",
"created" : "2019-04-03--19:10:11",
"id" : "NA",
"label" : "North America",
"levelIndex" : 1,
"levelName" : "Continent",
"type" : "location",
"usercount" : 2
}
}
}
},
"id" : "yjXidCKJuYZ71TNzYe9ob5Raaub2",
"ip" : "hidden",
"label" : "Anonymous"
}
}
}
exports.onUserAddToLocation = functions.database
.ref('/groups/location/Items/{itemId}/users/{userId}')
.onCreate((snapshot, context) => {
const itemId = context.params.itemId
const userId = context.params.userId
const groupCounterRef = admin.database().ref('/groups/location/Items/' + itemId + '/usercount');
return groupCounterRef.transaction(usercount => {
return (usercount || 0) + 1
}).then(result => {
const count = result.snapshot.val();
const userGroupsCounterRef = admin.database().ref('/users/' + userId + '/groups/location/Items/' + itemId + '/usercount');
userGroupsCounterRef.transaction(usercount => {
return count
})
})
})
This does the trick :
.ref('/groups/location/Items/{itemId}/users/{userId}')
.onCreate((snapshot, context) => {
const itemId = context.params.itemId
const groupCounterRef = admin.database().ref('/groups/location/Items/' + itemId + '/usercount');
return groupCounterRef.transaction(usercount => {
return (usercount || 0) + 1
}).then(result => {
const count = result.snapshot.val();
const usersRef = admin.database().ref("users").orderByKey();
usersRef.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot){
const userId = childSnapshot.key
const userLocationCountersRef = admin.database().ref('users/' + userId + '/groups/location/Items/' + itemId)
const hasThisGroup = childSnapshot.hasChild('/groups/location/Items/' + itemId)
if(hasThisGroup){
userLocationCountersRef.update({usercount:count})
}
})
})
})
})
This increments a counter for each user added to a location. After transaction success it copies that counter value to each user that has this location.

highchart change color of single bar in single category

I have a columnrange graph and want to define the color of a single bar line. If you see the second set in the picture. depending on a certain condition I would liek to change this to different color. $schedule[] = array($date_from, ( date('Y-m-d',strtotime($model['ProjectEndDate'])) > date('Y-m-d') )? $today*1000 : $date_to); if endate is not greater than today then change color to red.
How would I do this?
in view
$('#container').highcharts({
'chart':{
'type':'columnrange',
'inverted':true,
},
'exporting':{
'enabled':true
},
'title':{
'text':'Projects incomplete in 2013'
},
'xAxis':{
'categories':<?=$cat?>
},
'yAxis':{
'title':'Date',
'type':'datetime',
'dateTimeLabelFormats':{
'month':'%b'
},
'min':Date.UTC(2013,00,01)
},
'tooltip':{
formatter: function(){
return '<b>' +this.series.name + ':</b> '+ Highcharts.dateFormat('%e %b, %Y', this.point.low) + ' - ' + Highcharts.dateFormat('%e %b, %Y', this.point.high) +'<br/>' ;
}
},
'legend':{
'enabled':false
},
'series':[
{
'name':'Start - End',
'data':<?=$data?>
},
{
'name':'Forecast',
'data':<?=$schedule?>,
'color': 'green'
},
{
'name':'Actual',
'data':<?=$complete?>,
'color': 'yellow'
}
]
});
In my controller I have
public function actionGraph(){
$command = Yii::app()->db->createCommand("
SELECT
view_webprojectreport.PROJECT,
view_webprojectreport.StartDATE,
view_webprojectreport.ProjectEndDate,
view_webprojectreport.PERCENT,
view_webprojectreport.ASAAREA
FROM
view_webprojectreport
WHERE
view_webprojectreport.StartDATE >= '2013' AND
view_webprojectreport.ProjectEndDate IS NOT NULL AND
view_webprojectreport.PERCENT < 100
ORDER BY
view_webprojectreport.PERCENT DESC
")->queryAll();
$series = array();
$cat = array();
$totalLength = array();
$schedule = array();
$complete = array();
foreach ($command as $key => $model) {
$cat[] = $model['PROJECT'];
$date_from = (strtotime($model['StartDATE']) + 1*86400)*1000;
$date_to = (strtotime($model['ProjectEndDate']) + 1*86400)*1000;
$totalLength[] = array($date_from,$date_to);
$today = time();
$startdate = strtotime($model['StartDATE']);
$enddate = strtotime($model['ProjectEndDate']);
$diff_total = $enddate - $startdate;
$diff_today = $today - $startdate;
$percentage_date=round(($diff_today/$diff_total)*100,2);
$duration = ( ((strtotime($model['ProjectEndDate']) + 1*86400)*1000) - ((strtotime($model['StartDATE']) + 1*86400)*1000) );
$burn = ((time() )*1000) - ((strtotime($model['StartDATE']) + 1*86400)*1000);
$pBurned = $burn/$duration;
$time = $time = strtotime( ($date_from + $pBurned) );
//echo date('Y-m-d') . " : " . date('Y-m-d',strtotime($model['ProjectEndDate'])) . "<br>";
// place check for calculating if project end date is in past
$schedule[] = array($date_from, ( date('Y-m-d',strtotime($model['ProjectEndDate'])) > date('Y-m-d') )? $today*1000 : $date_to);
$percentage_to_get = round((float)$model['PERCENT'],2);
$percentage_of_days = ((int)$model['PERCENT'] == 0)? 0 : floor($diff_total/100*$percentage_to_get);
//echo date('Y-m-d', $startdate) . " : " . date('Y-m-d', $startdate + $percentage_of_days ) . "<br>";
//echo $startdate . " : " . ($startdate + $percentage_of_days) . "<br>";
$percentComplete = (($startdate + $percentage_of_days)+ 1*86400)*1000;
$complete[] = array($date_from,$percentComplete);
}
$series = array("series"=>array(
array(
'name'=>'Start - End',
'data'=>$totalLength
),
array(
'name'=>'Forecast',
'data'=>$schedule,
'color'=> 'green'
),
array(
'name'=>'Actual',
'data'=>$complete,
'color'=> 'yellow'
)
));
print_r($series);
$this->render('graph',array(
'cat'=>json_encode($cat),
"data"=>json_encode($totalLength),
"schedule"=>json_encode($schedule),
"complete"=>json_encode($complete),
"series"=>json_encode($series)
));
}
output of schedule
[[1357689600000,1372064004000],[1360972800000,1.3686588e+12],[1359158400000,1372064004000],[1.3630464e+12,1365721200000],[1359417600000,1372064004000],[1.3709916e+12,1372064004000],[1.3686588e+12,1372064004000],[1.3681404e+12,1372064004000],[1.3699548e+12,1372064004000],[1366930800000,1372064004000]]
How would I incorporate the color in this?
$schedule[] = array($date_from, ( date('Y-m-d',strtotime($model['ProjectEndDate'])) > date('Y-m-d') )? $today*1000 : $date_to);
I have found http://jsfiddle.net/Q2JMF/2/ and trying to implement but not working. graph displays nothing
My example on jsfiddle http://jsfiddle.net/shorif2000/z4HXX/2/
Your point should be object like :
{
y:10,
color: 'red'
}
So data should looks like:
data:[{
y:10,
color: 'red'
},4,5,6,7,7]
How to prepare correct structure:
http://php.net/manual/en/function.json-encode.php

How can I compare two dates in format dd mmm yyyy?

I would like to compare two dates in this format dd mmm yyyy, compare validators wont work because of the format and custom validator is server side validation. I would like to have a clinet side validation. What would be the best way to do it? if you have any examples or links please let me know.
I dont know if there are options availables with ajax, jquery or javascript that can do this?
Cheers
Since JavaScript natively converts from MMM dd, yyyy, this would be one approach:
var date1Str = "09 Sep 2011";
var date2Str = "04 May 2012";
var dateParts = date1Str.split(" ");
var newDateStr = dateParts[1] + " " + dateParts[0] + ", " + dateParts[2];
var date1 = new Date( newDateStr );
var dateParts = date2Str.split(" ");
var newDateStr = dateParts[1] + " " + dateParts[0] + ", " + dateParts[2];
var date2 = new Date( newDateStr );
if ( date1 > date2 )
...
There are tons of links on the net to do date parsing in JavaScript and plenty of libraries that make it easier. Remember that culture plays a part. "Oct" is in English but in German it will be "Okt".
Here's a simple class you can use to compare dates; the convert function has been adjusted to accommodate your format:
<script type="text/javascript">
var dates = {
convert:function(d) {
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[1],d[0],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
</script>
Credit for this class belongs to #some: https://stackoverflow.com/a/497790/879420

AS 3 functions optional value getting error

I have a gui class, The functions optional value getting error. If i am not passing the fillcolor and other optional values.
Error:
ReferenceError: Error #1069: Property fillColor not found on String and there is no default value.
AS 3.0
var windowBase:Sprite = UIClip("Sprite");
/* sliderClip = Gui.UIClip("MovieClip",{width:100, height:50, fillColor:0xFFFF0D, alpha:.7});
*/
function UIClip (type:String, params:object = '') {
var clip;
trace("Hello")
if (type == 'MovieClip') {
clip = new MovieClip ;
} else {
clip = new Sprite;
}
//trace(params + "params.fillColor " + params.fillColor)
if (params is Object) {
clip.graphics.beginFill ((params.fillColor != "") ? params.fillColor : 0xFFFFFF, params.alpha ? params.alpha : 1 );
clip.graphics.lineStyle (params.lineThickness != "" ? params.lineThickness : 1, params.borderColor ? params.borderColor: 0x000000);
clip.graphics.drawRoundRect (0,0,
(params.width != undefined ) ? params.width : 100,
(params.height != undefined) ? params.height : 100 ,
params.eW ? params.eW : 0,
params.eH ? params.eH : 0);
clip.graphics.endFill ();
//trace("Hello")
}
return clip;
}
How can I solve this?
Condition "if (params is Object)" is true. String is object, too.
I'm using null for optional params if they have no default value.
Try this:
function UIClip (type:String, params:object = null)
and test "if (params != null)"

Resources