Set array based on specific dates - javascript

Im looking to be able to set an arrays contents based on specific dates i.e.
if the date is the 25/12 then the array would look like the following
var compliments = [
'Happy Xmas!',
'Hope you been a good boy',
];
I would like to be able to do this over various dates and also have a default for the non special dates.
I am aware you would need to use the date function in javascript however I'm not experienced enough to work this out.

You can index your compliments with a date string.Try something like this.
var today = new Date(),
today_string = today.getMonth() + "-" + today.getDate();
compliments = {
"12-25": [
'Happy Xmas!',
'Hope you been a good boy'
],
"1-1": ["Happy new year!"],
"Default": ["Happy today ¬¬"]
};
console.log(compliments[today_string] || compliments["default"]]);

Use objects line array.
var compliments = {}
compliments['12/05'] = ['bla1', 'bla2'];
compliments['13/06'] = ['bla3', 'bla4'];
you can access them like this:
alert(compliments['12/05'][0] + compliments['12/05'][1]);

Related

How to convert 112889 (mmddyy) to 11/28/89 or 11/28/1989

How do we convert this unformatted date of 112889 (mmddyy) to specific format like 11/28/89?
console.log(new Date('112889'))
// I got this: Sat Jan 01 112889 00:00:00 GMT+0800
I have searched anywhere in google concerning this but found none specific answers.
Reference searches:
https://forums.asp.net/t/1987249.aspx?How+can+i+convert+Date+1365715800000+format+to+MM+dd+yyyy
Convert number into date using javascript
Im also thinking about momentjs formatting but couldn't find any doc about this or did i only missed it
Using the momentjs library you can specify what format your input string will come i.e. MMDDYY in this case.
var d = new moment("112889", "MMDDYY");
document.getElementById('dated').innerText = d.format('MM/DD/YYYY');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<div id="dated"></div>
Please have a look moment.js library. try this code
var date = moment('112889',"MMDDYY").format('MM/DD/YY');
console.log(data);
If you don't want to use a library and if you know that your input is always going to be of mmddyy format, you can do something like this:
var str = '112889';
var arr = str.match(/.{1,2}/g); // Splits string into 2 character chunks
var d = new Date(arr[2],arr[0],arr[1]);
console.log(d);
But this is quite not correct since if you give a string like 112804, JS (or anyone for that matter) will not know if it is 1904 or 2004 and it'll pick up 1904. In that case, you should specify explicitly:
var str = '112896';
var arr = str.match(/.{1,2}/g); // Splits string into 2 character chunks
var d = new Date(arr[2], arr[0], arr[1]); // new Date(yy,mm,dd);
var presentYear = Number((new Date()).getFullYear());
var dateYear = Number(d.getFullYear());
if (presentYear >= dateYear + 100) { // If adding 100 to year makes it greater than present year, then move to 2000s
d = new Date('20' + arr[2], arr[0], arr[1]);
}
console.log(d);

Google forms to calendar event issues with date format

So I have a very simple form that takes 3 inputs, a title, start and end date. I have tried to use a simple script to produce a calendar event. this can be seen below.
function onFormSubmit(e) {
var title = e.values[1];
var start_time = new Date(e.values[2]);
var end_time = new Date(e.values[3]);
CalendarApp.createEvent(title, start_time, end_time);
}
The issue I have is that as the date string is UK format (e.g. 05/12/2016 12:00:00) it is logging the events as 12th May as opposed to 5th December.
I am new to all of this so am looking for an elegant and simple solution I understand, not just to copy code I don't.
Thanks.
function convertUKDateToUSDate(date) {
const arr = date.split('/');
const temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
return arr.join('/');
}
will convert a date string with the prefix "DD/MM/" into "MM/DD/YYYY" format. Split turns the string into an array like ["DD", "MM", "YYYY HH:MM:SS"] and then the temporary variable is used to swap the "MM" and "DD" before the array entries are joined back together with the same character that was used to split them. You'll end up with a final onFormSubmit(e) like this:
function onFormSubmit(e) {
var title = e.values[1];
var start_time = new Date(convertUKDateToUSDate(e.values[2]));
var end_time = new Date(convertUKDateToUSDate(e.values[3]));
CalendarApp.createEvent(title, start_time, end_time);
}
Obviously I'm assuming e.values[2] and e.values[3] are strings. If they're Date objects already (or if you just want a shorter solution), then consider using the Moment.js (the premier Date object library) format function to convert between the formats. Normally I'd recommend using Moment anyways but you said you wanted something you could understand instead of copy.

Angular UI Grid date not formatting properly

I am using Angular's UI Grid to display a number of columns, but I cannot get the date column to format properly.
It is appearing as /Date(1451346632162-0000)/, etc.
I am trying to filter it in my gridOptions, but am having no luck:
// Removed Unrelated Column Defs
$scope.gridOptions.columnDefs = [
{ name: 'Date', field:'DateAdded',
/* First filter attempt */ cellTemplate: "<div>{{COL_FIELD | date:'dd-MM-yyyy' }}</div>",
/* Second Filter Attempt */ cellFilter:"date:'dd-MM-yyyy'"
}
I've tried variations of these that I found in the documentation with no luck - cellFilter: "date" and cellFilter: "longDate"
Any idea why these filter attempts are not working and the date is still appearing in this format?
I haven't been able to figure out what is stopping the regular filtering from working on the JSON date field, but here is the workaround I am using in the meantime (in case anyone has similar issues):
function formatDates(data) {
for (var i = 0; i < data.length; i++) {
var currentValue = data[i].DateAdded
var dateString = currentValue.substr(6);
var currentTime = new Date(parseInt(dateString));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = month + "/" + day + "/" + year;
data[i].DateAdded = date;
}
}
If anyone has any idea what is stopping the regular filtering from working please post. Thanks.
Assure that you are actually using a Date object. If you're receiving the data from a database, it may not be a Date. When you query the database on the client side, you may need to do as follows: data.map(function(datum){ datum.DateAdded = new Date(datum.DateAdded) }).
This assures all dates are proper date objects.

Javascript remove time from datetime

I am using full calendar and using the date from the eventclick
calEvent._start._i returns: 2015-12-01 09:00:00
and I want to compare it to another date although it is this format
2015-12-01
I have used
var date = new Date(calendarDate);
date.setHours(0,0,0,0);
which returns an invalid date format
I have also used
var calDate = _longDateFormat(calendarDate, "dd-mm-yy");
which errored on the javascript
Nothing seems to work, including dateFormat.
Ideas?
I was facing the same problem and I didn't want to use specific formatting options because I wanted the date to be displayed in the correct local format. I ended up using a simple regex replace, maybe this approach will help you as well:
new Date().toLocaleString().replace(/\s\d{2}:\d{2}:\d{2,4}$/, ''))
You could do something like this:
function checkWhetherCorrectDate(requestedDate, calendarDate) {
var date1 = new Date(calendarDate.replace(/-/g,'/'));
var date2 = new Date(requestedDate);
date1.setHours(date2.getHours(), date2.getMinutes(), date2.getSeconds());
return date1.getTime() === date2.getTime();
}
document.write(checkWhetherCorrectDate("2015-12-01", "2015-11-30 09:00:00") + '<br />')
document.write(checkWhetherCorrectDate("2015-12-01", "2015-12-01 09:00:00") + '<br />')

Formatting a JSON Date with javascript

I am returning a JSON object from my web service method. The object has some dates in it and so the generated JSON is like the following:
{"d": [
{"PeriodID":8,"Period":"072011","BeginDate":"\/Date(1294268400000)\/"},
{"PeriodID":2,"Period":"052011","BeginDate":"\/Date(1293836400000)\/"}
]}
I am trying to convert this data in a string to be added as <option> elements in an HTML select. This is my code:
var rtypes = data.d;
$.each(rtypes, function (key, value) {
var text = value.Period + " - " + "from " + eval(value.BeginDate.slice(1, -1));
var option = $("<option></option>").attr("value", value.PeriodID).text(text);
$('#rpCombo').append(option);
});
Now the questions:
Can I format the date contained in the Period field (e.g. 072011) as a "July 2011"?
How can I convert the result of eval(value.BeginDate.slice(1, -1)) that is for instance something like "Wed July 14......" into something like "14/07/2011"?
Thanks for helping
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse
For example
// create 1 of June 2011 from Jun 2011
var period = new Date(Date.parse("1 "+period));
Here is what I think you want
<script>
var months = ["Jan","Feb","Mar","Apr","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
var result = {"d": [
{"PeriodID":8,"Period":"072011","BeginDate":1294268400000},
{"PeriodID":2,"Period":"052011","BeginDate":1293836400000}
]}
var aPeriod, period, periodMM, periodYYYY, periodText, beginDate, beginMM, beginDD;
for (var i=0,n=result.d.length;i<n;i++) {
aPeriod = result.d[i];
// period = new Date(aPeriod.Period.slice(2),aPeriod.Period.slice(0,2)-1,1,0,0,0);
// periodText = months[period.getMonth()]+" "+period.getFullYear();
periodMM = parseInt(aPeriod.Period.slice(0,2),10);
periodYYYY = aPeriod.Period.slice(2);
periodText = months[periodMM]+" "+periodYYYY;
beginDate = new Date(aPeriod.BeginDate);
beginDD = beginDate.getDate();
if (beginDD<10) beginDD="0"+beginDD;
beginMM = beginDate.getMonth()+1;
if (beginMM<10) beginMM="0"+beginMM;
periodText += " "+beginDD+"/"+beginMM+"/"+beginDate.getFullYear();
alert(periodText)
}
</script>
Not sure on the scale of your project, but I was doing a lot with dates recently and benefitted by implementing javascript extensions on the javascript Date object. This will make your life soooo much easier as it has for me and will take care of the above scenario and then some.
There is a very good article here: Javascript/Json Date Parsing
I did need to tweak it a little, but no looking back since implementing this approach.

Categories

Resources