Convert 'Month and Year' string into Date object using JS and Jquery - javascript

I have two arrays ( i made them from jQuery from a table), the first is the end date, and the second is the start date. The elements are strings:
["June, 2012", "June, 2012", "August, 2011", "April, 2013", "August, 2010", "August, 2010", "April, 2013", "April, 2012", "April, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012", "June, 2012"]
["November, 2011", "April, 2012", "May, 2008", "May, 2007", "November, 2007", "May, 2007", "June, 2006", "June, 2007", "April, 2006", "January, 2008", "April, 2001", "April, 2001", "April, 2006", "April, 1998", "April, 1998", "September, 2008", "August, 2010", "August, 2009", "August, 2010", "August, 2009", "August, 2010", "August, 2010", "August, 2010", "January, 1997", "January, 1997", "January, 2010", "January, 2007", "April, 2010"]
I am trying to get the elapsed time between each set of indices. I would assume that I have to convert these strings to a Date Object date() then do the calculation to get the elapsed time, then truncated it to just the month and year using something like this:
function convertDate(passedDate) {
var m = new Array(7);
var y = passedDate.getFullYear();
m[0] = "January";
m[1] = "February";
m[2] = "March";
m[3] = "April";
m[4] = "May";
m[5] = "June";
m[6] = "July";
m[7] = "August";
m[8] = "September";
m[9] = "October";
m[10] = "November";
m[11] = "December";
return m[passedDate.getMonth()] + "months and " + y + " years;
};
Here is the fiddle and here are my questions:
Is there anyway to do this without changing it to a date object, since I'm not interested in the days or time?
Is there another approach you would suggest than trying to convert to date for the elapsed date math formula, then converting back to a string?
How would I identify the sister elements of the current element, so that I could avoid using a double nested loop? ( will also ask this in a different question since it addresses a different topic)
Thanks for helping me, as I'm trying to make an interactive resume with selectable attributes, and I'm including some data so I don't have to answer all the basic information to recruiters who cold call.

Really, all you need is a map from month names to numbers. You can build one like this:
var monthNames = [ "January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December" ]
var monthNumber = {}
for (var i=0; i<monthNames.length; ++i) {
monthNumber[monthNames[i]] = i;
}
Now you have, e.g., monthNumber['October'] == 9. Then you can turn one of your strings into a month number and year. If you then turn that into an absolute month number (year * 12 + month), you can just subtract to get the elapsed months.
function stringToMonthNumber(monthYear) {
var parts = monthYear.split(/\s*,\s*/)
var month = monthNumber[parts[0]]
var year = parts[1] - 1
return year * 12 + month
}
function elapsedMonths(startString, endString) {
return stringToMonthNumber(endString) - stringToMonthNumber(startString)
}
Then this:
elapsedMonths("November, 2011", "June, 2012")
returns 7.

Related

Count Full Year from Date String

I'm currently working in Node with mongoose as a database. I have two models product and customer .whenever a customer buy a product, the current Date gets stored in SellingDate attribute of the product. Now the thing I want to achieve is that when we give a random Date as input, it should compare it with all Selling dates of all products up to one year, and return us COUNT OF ALL DATES THAT LIE BETWEEN ONE YEAR. For example , if we have 5 records in database i.e
{
"Sun Feb 25 2015" , "Fri Mar 25 2015" , "Sat Dec 25 2015" , "Mon Feb 25 2016"
}
and I give " Sun Feb 25, 2015" as input it should return 2 as output because we have two dates between Feb 2015 - Feb 2016 .... and it should compare dates in String format because I store the date in "Day Month Date Year" format ...
You could do an aggregation where you first convert the date strings to a date using $toDate and also keep track of the year using $year. Then you can $match all documents within the given date range, and finally $group by the year and $count:
YourModel.aggregate([
{ "$addFields": {
"year":{ "$year": {
"$toDate": "$date"
}
} }},
{
$match: {
// define your range of years here, it would be 2015 - 2016 in your case
year: {$gte: 2016, $lte: 2020}
}
},
{
$group: {
_id: {year: "$year"}
}
},
{
$count: "totalCountPerYearRange"
}
]);
As long as the date strings are in an array - using [] NOT {} (which defines an object that requires property:value pairs), then you can convert the strings into dates and do simple comparisons. The following will return an array, where you can simply get the array's length for the count.
let myDates = [
"Thu Jan 07 2016",
"Tue Mar 01 2016",
"Wed May 25 2016",
"Sat Jun 25 2016",
"Sun Aug 14 2016",
"Fri Nov 18 2016",
"Fri Jan 06 2017",
"Sun Apr 16 2017",
"Sun May 21 2017",
"Sun Jul 30 2017",
"Fri Sep 22 2017",
"Sun Nov 12 2017",
"Sun Dec 24 2017"
]
let firstDate = new Date("Wed May 25 2016");
let lastDate = new Date("Thu May 25 2017");
let matches = myDates.filter(d => {if (new Date(d) >= firstDate && new Date(d) <= lastDate) return d});
console.log(matches);
console.log(matches.length);

"Error while interpolating {{ " using angularjs in my code

i am getting error when day is sunday.monday to saturday its working when day is sunday i am getting error
Error: Error while interpolating: {{isOpen(dealer.Day)}}
TypeError: Cannot read property 'replace' of undefined
var ds= 'Sun Dec 13 2015 14:04:42 GMT+0530 (India Standard Time)';
var now = new Date(ds);
if you change day and date its working fine
var ds= 'Sat Dec 12 2015 14:04:42 GMT+0530 (India Standard Time)';
var now = new Date(ds);
i have added my code below pls help me out.
angular.module('myApp', [])
.controller("myCntrl", function($scope, $filter) {
$scope.isOpen = function(dealerSchedule) {
var ds= 'Sun Dec 13 2015 14:04:42 GMT+0530 (India Standard Time)';
var now = new Date(ds);
//var now = new Date();
//---if you change day and date you will not get error
//var ds= 'Sat Dec 12 2015 14:04:42 GMT+0530 (India Standard Time)';
//var now = new Date(ds);
var times = dealerSchedule[Object.keys(dealerSchedule)[now.getDay() - 1]].replace(/(\d\d\:\d\d)(AM|PM)/g, '1/1/1900 $1 $2').split(" - ");
var nowTime = new Date('1/1/1900 ' + now.toLocaleTimeString(navigator.language, {
hour: '2-digit',
minute: '2-digit',
hour12: true
}));
console.log(nowTime);
var response = (times == "Leave" ? "Leave" : (nowTime >= new Date(times[0]) && nowTime <= new Date(times[1]) ? "Open Now" : "Closed Now"));
return response;
};
$scope.dealers = [{
S_Email_id: "aditiya#gmail.com ",
status: "",
Store_Name: "Adtiya Samsung Store",
Day: {
"monday": "09:10 AM - 06:30 PM",
"tuesday": "09:10 AM - 12:00 PM",
"wednesday": "09:10 AM - 06:30 PM",
"thursday": "09:10 AM - 06:30 PM",
"friday": "09:10 AM - 06:30 PM",
"saturday": "10:15 AM - 04:15 PM",
"sunday": "10:15AM - 04:15PM"
},
}, {
S_Email_id: "rajs#gmail.com",
status: "",
Store_Name: "sri shakthi mobile service",
Day: {
"monday": "09:00 AM - 06:00 PM",
"tuesday": "09:00 AM - 06:00 PM",
"wednesday": "09:00 AM - 06:00 PM",
"thursday": "09:00 AM - 06:00 PM",
"friday": "09:00 AM - 06:00 PM",
"saturday": "09:00AM - 06:00PM",
"sunday": "Leave"
},
}, {
S_Email_id: "sprtive23#gmail.com",
status: "",
Store_Name: "sun mobile service center ",
Day: {
"monday": "08:30 AM - 07:30 PM",
"tuesday": "02:30 PM - 07:30 PM",
"wednesday": "08:30 AM - 07:30 PM",
"thursday": "08:30 AM - 07:30 PM",
"friday": "08:30 AM - 07:30 PM",
"saturday": "08:15 AM - 02:15 PM",
"sunday": "8:15 AM - 12:15AM"
},
}, {
S_Email_id: "super#gmail.com ",
status: "",
Store_Name: "ragu mobile service center ",
Day: {
"monday": "10:00 AM - 10:00 PM",
"tuesday": "10:00 AM - 10:00 PM",
"wednesday": "10:00 AM - 04:00 PM",
"thursday": "10:00 AM - 10:00 PM",
"friday": "10:00 AM - 10:00 PM",
"saturday": "leave",
"sunday": "leave"
},
}]
//var date = new Date();
//$scope.hhmmsstt = $filter('date')(new Date(), 'hh:mm:ss a');
//console.log($scope.hhmmsstt);
})
//]]>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.1/angular.min.js'></script>
<div ng-app="myApp">
<div ng-controller="myCntrl">
<label>Search on Label</label>
<br>
<input ng-model="query" type="text" placeholder="Search for name" />
<br>
<br>
<div ng-repeat="dealer in dealers">
{{dealer.Store_Name}}
<br>{{dealer.S_Email_id}}
<br>{{dealer.Day}}
<br>
<input type="button" value="order" />
<span>{{isOpen(dealer.Day)}}</span>
<br>
<br>
<br>
</div>
</div>
</div>
check my code i am getting error
pls don't give down vote bcoze i dono why its not working i am new to technology.help me out
The problem is with
now.getDay() - 1 will fail for Sunday (getday() will return 0)
You should put a check for that like similar,
var dayCheck = now.getDay() == 0 ? 6 : now.getDay() - 1;
var times = dealerSchedule[Object.keys(dealerSchedule)[dayCheck]].replace(/(\d\d\:\d\d)(AM|PM)/g, '1/1/1900 $1 $2').split(" - ");
The error is coming from:
var times = dealerSchedule[Object.keys(dealerSchedule)[now.getDay() - 1]].replace(/(\d\d\:\d\d)(AM|PM)/g, '1/1/1900 $1 $2').split(" - ");
It's a bit confusing of what you are tying to achieve on this line?
Also as a note for future if you're going to put code into your questions removed commented out code as its not needed.
Also I'd consider upgrading you're angular version.
Issue with your code is in this statement
now.getDay() - 1
Days in Date object are zero based indices, so on Sunday, getDay() will return 0 and the above statement will evaluate to -1 which is a not valid index in your keys array of your Day object. To look up the day properly from date's getDay(), I suggest you use the index returned by getDay() and change your Day object so that sunday comes first and in sync with the spec like below.
Day: {
"sunday": "10:15AM - 04:15PM",
"monday": "09:10 AM - 06:30 PM",
"tuesday": "09:10 AM - 12:00 PM",
"wednesday": "09:10 AM - 06:30 PM",
"thursday": "09:10 AM - 06:30 PM",
"friday": "09:10 AM - 06:30 PM",
"saturday": "10:15 AM - 04:15 PM"
}
Also there are few inconsistencies in your JSON object for Day
Sometimes you used leave and sometimes its Leave. It should be same for all Day objects
For the 3rd dealer (sun mobile service center), you mentioned sunday timings as 8:15 AM - 12:15AM while it should be `8:15 AM - 12:15 PM' (from morning 8.15 - afternoon 12.15)
Correcting all these consistencies, adding some new logic for deriving dates from your Day object, here's a working Pen which will display Open Now / Closed Now / Leave accordingly.
Hope this helps :)

Custom Sorting By 24-hour clock Time in Backbone/Javascript

I have backbone collection which consists of dates and 24-hour clock times. I would like to be able to sort my collection by time.
So since a normal sort functionality would sort (as an example) 1:00, 17:00, and 19:00 as such, I am trying to display 17:00, 19:00, 1:00 in that order. 1:00 of the next day proceeds 19:00 in time, in this case.
Since this case only occurs when a value is less than or equal to 12, the simplest solution seems to be: sort those values greater than 12; sort values less than 12; append sorted values less than 12 to values greater than 12. So two separate sorted lists.
comparator: function( a, b ) {
if(!this.sortColumn ) return 0;
if(sortColumn == 'time') {
switch (a.get('time')) {
case a > 12: return 1;
case a <= 12: return 2;
}
}
}
This is a rough idea that I've had. This doesn't sort the two respective groups. The idea being that the case where it's greater than 12 precedes the case where it's less than 12, but they will be unsorted.
EDIT: Note that all the events occur after 12:00 PM on Day 1 and before 12:00 PM of the next day, Day 2. This is why dates like 1:00 will be after dates like 19:00.
Any advice would be fantastic.
Thanks
You can define your comparator function as a "sortBy" :
"sortBy" comparator functions take a model and return a numeric or
string value by which the model should be ordered relative to others.
The goal is then to produce a sorting value that corresponds to your requirements. As #Pointy noted in the comments, adding 24 to the times before 12:00 would do the trick
For example
var C = Backbone.Collection.extend({
comparator: function (m) {
var t = m.get('time'),
h = parseInt(t.substr(0, 2), 10),
m = parseInt(t.substr(3), 10);
if (h<12) h = h+24;
return h *60 + m;
}
});
var c = new C([
{time: '01:17'},
{time: '01:00'},
{time: '12:00'},
{time: '07:00'},
{time: '15:00'}
]);
console.log(c.pluck('time'));
http://jsfiddle.net/nikoshr/5srqn5b4/
I dont see the issue with just ordering them by the actual number..
var times = [];
// generate some data..
// [1:00, 1:30, 2:00 ...]
for(var i=0; i < 24; i++){times.push(i.toString() + ':00');
times.push(i.toString() + ':30')}
// standard sorting
console.log(_.sortBy(times, function(num){ return num}))
> ["0:00", "0:30", "10:00", "10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "1:00", "1:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30", "2:00", "2:30", "3:00", "3:30", "4:00", "4:30", "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30", "9:00", "9:30"]
// improved sorting
console.log(_.sortBy(times, function(num){ var key = parseInt(num.split(':')[0]); if (key >= 12) {return key - 12} return key + 20 }))
> ["12:00", "12:30", "13:00", "13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00", "22:30", "23:00", "23:30", "0:00", "0:30", "1:00", "1:30", "2:00", "2:30", "3:00", "3:30", "4:00", "4:30", "5:00", "5:30", "6:00", "6:30", "7:00", "7:30", "8:00", "8:30", "9:00", "9:30", "10:00", "10:30", "11:00", "11:30"]

Google Chart - Customize column label Grouping

Is it possible to customize column label in google chart? like grouping similar data to one label
google.load('visualization', '1', {
packages: ['table']
});
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month'); // Implicit domain label col.
data.addColumn('number', 'Value'); // Implicit series 1 data col.
data.addColumn({
type: 'string',
role: 'tooltip'
}); // annotation role col.
data.addColumn({
type: 'string',
role: 'domain'
}); // annotation role col.
data.addRows([
["March", 26075, "17 - Mar - 2014 | 26075", "March"],
["", 26150, "18 - Mar - 2014 | 26150", "March"],
["", 25400, "28 - Mar - 2014 | 25400", "March"],
["April", 26000, "01 - Apr - 2014 | 26000", "April"],
["", 28300, "28 - Apr - 2014 | 28300", "April"],
["", 28500, "29 - Apr - 2014 | 28500", "April"],
["", 29000, "30 - Apr - 2014 | 29000", "April"],
["May", 29400, "02 - May - 2014 | 29400", "May"],
["", 27800, "30 - May - 2014 | 27800", "May"],
["June", 27325, "02 - Jun - 2014 | 27325", "June"],
["", 27150, "19 - Jun - 2014 | 27150", "June"],
["", 29000, "26 - Jun - 2014 | 29000", "June"],
["", 29300, "27 - Jun - 2014 | 29300", "June"],
["", 28700, "30 - Jun - 2014 | 28700", "June"],
["July", 28175, "01 - Jul - 2014 | 28175", "July"],
["", 26150, "21 - Jul - 2014 | 26150", "July"],
["", 26000, "24 - Jul - 2014 | 26000", "July"],
["", 26575, "25 - Jul - 2014 | 26575", "July"],
["August", 26700, "04 - Aug - 2014 | 26700", "August"],
["", 25900, "26 - Aug - 2014 | 25900", "August"],
["", 25850, "27 - Aug - 2014 | 25850", "August"],
["", 25900, "28 - Aug - 2014 | 25900", "August"],
["", 26000, "29 - Aug - 2014 | 26000", "August"],
["September", 25500, "01 - Sep - 2014 | 25500", "September"],
["", 25800, "08 - Sep - 2014 | 25800", "September"],
["", 25775, "09 - Sep - 2014 | 25775", "September"],
]);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {});
}
google.setOnLoadCallback(drawVisualization);
<script src="https://www.google.com/jsapi"></script>
<div id="table"></div>
I have removed a lot of data, but I want the data to be grouped by month and the chart only show month's name as the column.
Any suggestion?

Inserting events from json object to fullcalendar

Hello folks I am trying to utilize the fullcalendar to display some holidays I have acquired from a json object.
JSON looks as follows.
var holidayObj = [
{
"holidayName" : "Boxing Day",
"holidayStart" : "May, 26 Oct 2014 13:00:00 EST",
"holidayEnd" : "May, 26 Oct 2014 13:00:00 EST"
}
{
"holidayName" : "Some other Day",
"holidayStart" : "May, 23 Oct 2014 13:00:00 EST",
"holidayEnd" : "May, 23 Oct 2014 13:00:00 EST"
}
];
My JS code to display the events on fullcalendar is as follows.
$.each(holidayObj, function(i, item) {
holidayNameText = item.holidayName;
console.log(holidayNameText); //"Boxing Day"
holidayStart = item.holidayStart; //May, 26 Oct 2014 13:00:00 EST
holidayEnd = item.holidayEnd; //May, 26 Oct 2014 13:00:00 EST
var eventObject = {
title: holidayNameText,
start: holidayStart,
end : holidayEnd,
allDay:true
};
$('#calendar').fullCalendar('renderEvent', eventObject, true);
console.log(eventObject.start);
});
For some reason the events don't seem to be populating on the calendar. Can anyone help me identify what the cause might may be?
Thank you.
You are missing a comma to separate the array elements:
var holidayObj = [{
"holidayName": "Boxing Day",
"holidayStart": "May, 26 Oct 2014 13:00:00 EST",
"holidayEnd": "May, 26 Oct 2014 13:00:00 EST"
}, {
"holidayName": "Some other Day",
"holidayStart": "May, 23 Oct 2014 13:00:00 EST",
"holidayEnd": "May, 23 Oct 2014 13:00:00 EST"
}];
By fixing it, it works fine (see the events in October).
Demo: http://jsfiddle.net/IrvinDominin/EGbHt/

Categories

Resources