So I have been tasked with creating a jQuery slideshow from an XML file with a timing mechanism to change the images based on date. I have the slideshow working from the XML, but I am struggling with adding the date feature. I would like to be able to "turn on" and "turn off" images based on the onDate and offDate. I understand Javascript is not the best way to show things based on date, but there are limits within the current site structure that prevent server side timing. So I would like to have the ability to load up say 10 images, and then only show three based on what today's date is, and what the onDate/offDate are.
This is the logic I was thinking.... If today is < onDate .hide or if today is > offDate .hide else .show
Where I am struggling
The correct way to enter the date in the XML file.
Parsing the date from XML into something that Javascript and in turn jQuery can use to compare today's date with the date in XML and show the image accordingly.
Once the date has been established figuring out a way to show or hide the specific image based on date.
Any help would be greatly appreciated.
XML
<eq-banner>
<id>1</id>
<url>linktopage.html</url>
<img>image.jpg</img>
<dept>equipment</dept>
<onDate>12/01/2010</onDate>
<offDate>12/31/2010</offDate>
<copy>FREE Stuff</copy>
</eq-banner>
jQuery
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "rotationData.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(equipment) {
$(equipment).find('eq-banner').each(function() {
var id = $(this).attr('id');
var dept = $(this).find('dept').text();
var url = $(this).find('url').text();
var img = $(this).find('img').text();
$('<div class="'+dept+'"</div>').html('<img src="images/'+img+'" /><br />').appendTo('#apparel')
$("#equipment").cycle({
fx:"fade",
speed:100,
timeout:5000
});;
});
}
</script>
HTML
<div id="equipment">
</div>
If you trust the data quality of the XML source, specifically that the dates are all well-formed as in your sample, it's pretty easy to turn that into a JavaScript "Date" object:
var str = "12/31/2010";
var pieces = str.split('/');
var date = new Date(~~str[2], ~~str[0] - 1, ~~str[1]);
(The ~~ trick converts the strings to numbers; do that however you prefer.) Also months are numbered from zero, and hence the subtraction.
Comparing dates works perfectly well in JavaScript, or you can call the ".getTime()" method on a date to explicitly get a "milliseconds since the epoch" value to compare instead.
As to how you'd show/hide the images, I'd be inclined to conditionally add a class to elements to be hidden (or shown; whichever makes the most sense).
XML doesn't have a "correct" way of handling dates, and JavaScript can parse just about anything. However, the most JS-friendly format would be something like "October 20, 2011" with the time optionally added in "12:34:56" format. A string like that can be fed directly to the new Date() constructor and be parsed correctly regardless of location.
datestr = "October 20, 2011";
date = new Date(datestr);
To compare Date objects, just use < or > -- however, a JS Date object contains a time element which will also be compared. So if you create a new Date object for the present with var now = new Date(); and compare it to var dat = new Date("string with today's date"); you'll find that dat is less than now because dat has time 00:00:00 while now has the present time. If this is a problem, you'll have to explicitly compare Date.getDate(), Date.getMonth() and Date.getFullYear() all at once. ( http://www.w3schools.com/jsref/jsref_obj_date.asp )
Related
I am currently writing a custom function in Google App Scripts. Right now I am struggling. I defined an argument to take input from a date cell and change the format.
e.g 9/16/2010 to 09.16.2010 where a given column has the former date and the function outputs the latter.
The output is a string, but I can't seem to find any information on this specific text editing feature of javascript.
It's also worth mentioning that the date in a given column is based on a form output, I am not calling a specific short date in the code, so rather this is more string manipulation than date formatting
Any help is appreciated.
/**
*Generates a Trip Key
*
*#param DateColumn Date
*#param SchoolColumn School name
*#param LocationColumn Location
*#customfunction
*/
function GENERATEKEY(DateColumn) {
var Date = DateColumn
const dateStr = Date;
const dateArr = dateStr.split('/');
dateArr[0] = ('0' + dateArr[0]).slice(-2);
dateArr[1] = ('0' + dateArr[1]).slice(-2);
const DateEdited = dateArr.join('.');
return neWDateStr; //gives 00.00.0000
//var Key = Date SchoolColumn "#" LocationColumn
}
Date is a built-in object. It should not be used as a variable name.
While const is allowed in Google Apps Script, it's not fully supported (it doesn't work as the ECMAScript states). IMHO it's better to use var to avoid "confusions".
In Google Sheets, based in the spreadsheet settings, change values entered in supported date-time format into serial numbers and use a number format to display it as date, time, date-time or duration. When a serial number displayed as date, date-time, time or duration is passed to a custom function, Google Apps Script convert it to a Date object.
To return a date formatted use Utilities.formatDate(...) Details in https://developers.google.com/apps-script/reference/utilities/utilities#formatdatedate,-timezone,-format
Related
How to format the date in this Google Apps Script
You could simply use inbuilt TEXT function:
=TEXT(A2,"mm.dd.yyyy")
The reason your current script(as provided in one of the previous answers) doesn't work is because the argument DateColumn is not of type String. You can convert the date object to a specific string and format it accordingly or use inbuilt Utilities library.
function DOWHATTEXTDOES(dateColumn) {
return Utilities.formatDate(dateColumn, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "yyyy.MM.dd")
}
Essential Reading:
Custom function Data type
Date
You can do something like this
"02/05/2009".split('/').join('.');
Get and Set the numberFormat for the active range
Sheet.getRange().setNumberFormat("mm.dd.yyyy");
Here's a dialog and function that I use sometimes for playing around with different formats. I find it a lot easier and quicker that using the spreadsheet functions.
The top function is a dialog that reads and displays the current format for the active range and has a textbox and button for each cell in the in the active range that allows you to set the number format and see the change immediately.
function getandSetActiveRangeFormats() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var rg=sh.getActiveRange();
var fA=rg.getNumberFormats();
var html='<style>th,td{border:1px solid black;}</style><table><tr><th>Item</th><th>A1 Notation</th><th>Number Format</th><th>Enter Format</th><th>Set Format</th></tr>';
var item=1;
var row=rg.getRow();
var col=rg.getColumn();
fA.forEach(function(r,i){
r.forEach(function(c,j){
var txt=Utilities.formatString('<input type="text" id="RC-%s-%s" />',row+i,col+j);
var btn=Utilities.formatString('<input type="button" value="Set Form" onClick="setFormat(%s,%s);" />',row+i,col+j);
html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',item++,sh.getRange(row + i,col + j).getA1Notation(),fA[i][j],txt,btn);
});
});
html+='</table><input type="button" value="Exit" onClick="google.script.host.close();" />';
html+='<script>function setFormat(row,col){var f=document.getElementById("RC-"+row+"-"+col).value;google.script.run.setFormat(row,col,f);}</script>';
var ui=HtmlService.createHtmlOutput(Utilities.formatString(html));
SpreadsheetApp.getUi().showModelessDialog(ui, "Display Cell Formats")
}
function setFormat(row,col,format) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
sh.getRange(row,col).setNumberFormat(format);
}
Animation:
I'm using the Foundry template on Squarespace and I need to change the date format on post pages from english to portuguese. Instead of "May 6" I need "6 Mai". In Brazil we use the pattern dd/mm/yyyy. In this case I just want the day and month, and also translate all the months (to: Jan, Fev, Mar, Abr, Mai, Jun, Jul, Ago, Set, Out, Nov, Dez).
I already saw people solving this for others languages there. But not to portuguese or on the Foundry template. It's possible to make a code-injection on Squarespace, on the head or footer. I just need a Javascript that can do that, overwriting the theme's default date format.
I would approach it via the following Javascript, inserted via code injection. Note that although some of the month abbreviations are the same, I've included them for clarity and so that it may be more reusable for others. Also, the abbreviations I've used for the keys (that is, the original month abbreviations) may not be what Squarespace actually uses, so they may need to be updated.
<script>
(function() {
var dates = document.getElementsByClassName("dt-published date-highlight");
var newDate;
var i,I;
// Create object with 'source' keys on the left, and 'output' values on the right.
var months = {
"Jan":"Jan",
"Feb":"Fev",
"Mar":"Mar",
"Apr":"Abr",
"May":"Mai",
"Jun":"Jun",
"Jul":"Jul",
"Aug":"Ago",
"Sep":"Set",
"Oct":"Out",
"Nov":"Nov",
"Dec":"Dez"
};
// Loop through all dates, replacing months and reordering display.
// - Trim extra white space from beginning and end of date.
// - Replace multiple consecutive spaces with a single space.
// - Split by space into an array.
// - Replace month text based on 'months' object key:value pairs.
// - Convert array to string, rearranging display order of elements.
// - Set new date HTML.
for (i=0, I=dates.length; i<I; i++) {
newDate = dates[i].innerHTML.trim();
newDate = newDate = newDate.replace(/ +/g, ' ');
newDate = newDate.split(" ");
newDate[0] = months[newDate[0]];
newDate = newDate[1] + " " + newDate[0];
dates[i].innerHTML = newDate;
}
})();
</script>
I am following this Set multiple jQuery Datepickers' value based on one jQuery Datepicker's selected date which is already asked by me and also received answer as well.
I have following multiple dates on a page and change on first date picker will change values for other date pickers on the screen.
First date picker is one which value will changes values for other date pickers.
Note: Please note that I want to display Date Picker from Image and don't want to use input type as text
I want to know the best way to store this values to server. You can see my current code same as suggested in answer in above question.
$("#datepicker1, #datepicker2, #datepicker3, #datepicker4").datepicker();
$("#datepicker1").datepicker("option", "onSelect", function (dateText, inst) {
var date1 = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);
var date2 = new Date(date1.getTime());
date2.setDate(date2.getDate() + 1);
$("#datepicker2").datepicker("setDate", date2);
var date3 = new Date(date1.getTime());
date3.setDate(date3.getDate() + 2);
$("#datepicker3").datepicker("setDate", date3);
var date4 = new Date(date1.getTime());
date4.setDate(date4.getDate() + 3);
$("#datepicker4").datepicker("setDate", date4);
});
But I would like to implement it through js array and then want to save data from PHP.
Can anybody guide me on this?
If there would be little code help then it will be very great help for me.
If you want to store your data asynchronously (without full page reload) you can simply make use of jQuerys post function:
$('#submit_btn').click(function(){
$.post( "handler.php", {
dp1: $("#datepicker1").val(),
dp2: $("#datepicker2").val(),
dp3: $("#datepicker3").val(),
dp4: $("#datepicker4").val()
})
.done(function( data ) {
alert( "Data successfully stored!");
});
});
Suggesting that you use an HTML submit button*:
<input type="submit" id="submit_btn" value="send" />
In this example, you would have a handler.php file in the same directory. In this file, you could access the datepicker values through
$_POST['dp1'], $_POST['dp2'] etc.
If you really want to pass an array for some reason (I would pass 4 values just like this), you should transfer a JSON object and decode it in php via
json_decode()
Hope this helps!!
*regarding your markup from the post you referenced, I would suggest packing all the datepickers in a element. Although not necessary, this is syntactically correct and allows you to bind to the "submit" event instead of the click event on the button.
I'm using DateTextBox as one of many controls in my screen. I register them in one place and then batch set values to them in loop, calling set('value', val) on each of them. All controls behave correctly, only the DateTextBox won't accept the data from server.
Initially java's Date was serialized as long (ex. 1280959200000), but when I've changed to ISO format (ex. "2010-08-04T22:00:00.000+0000") it isn't accepted either. But both are accepted date formats for new Date() constructor.
On the output I get the date value in ISO format: "2013-08-04T22:00:00.000Z" so it should be also accepted on input.
What can I do with DateTextBox to make it accept values in all formats supported by JavaScript's Date object, or one of the formats that can be returned from my server?
I think the fundamental problem is that the Javascript built-in Date object only accepts certain formats, and Dojo is relying on that built-in-behavior. At work, we have a similar issue, where lots of legacy PHP code is accustomed to passing dates around in a Mysql-derived format (ex. YYYY-MM-DD HH:MM:SS)
Our current workaround is to subclass dijit/form/DateTextBox, which also lets us impose some UI improvements. When something tries to set a value which isn't already a Date object and looks like a MySQL datetime, this code re-forms it to match ISO-8601 and passes it on through.
Dojo 1.9 code for a custom version of DateTextBox:
define([
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/_base/array",
"dijit/form/DateTextBox"
], function(declare, lang, array, DateTextBox){
var clazz = declare([DateTextBox], {
_mysqlStyleExp : /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})$/,
postMixInProperties: function(){ // change value string to Date object
this.inherited(arguments);
this.constraints.datePattern = "yyyy-MM-dd"; // Affects display to user
},
_convertMysqlDateToIso: function(value){
value = lang.trim(value);
var matches = this._mysqlStyleExp.exec(value);
if(matches !== null){
// Put the "T" in the middle and add fractional seconds with UTC
// timezone
// If your MySQL dates are NOT in UTC, obviously this will screw things up!
return matches[1] + "T" + matches[2] + ".000Z";
}else{
return null;
}
},
_setValueAttr : function(/*Date|String*/ value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){
/*
We want to be slightly more permissive in terms of the strings that can be set in order to support
older code... But someday it'd be nice to standardize on Date.toJSON, so warn.
*/
if(typeof(value) === "string"){
var isoDate = this._convertMysqlDateToIso(value);
if(isoDate !== null){
console.warn("Converting non-ISO date of "+value);
value = isoDate;
}
}
this.inherited(arguments);
}
});
return clazz;
});
Note that this only affects data flowing into the Dojo widget.
The docs say:
The value of this widget as a JavaScript Date object, with only
year/month/day specified.
So instead of this (which I assume you're currently doing):
new dijit.form.DateTextBox({value: "2010-08-04T22:00:00.000+0000"}, domNode);
Do this:
var myDate = new Date("2010-08-04T22:00:00.000+0000");
new dijit.form.DateTextBox({value: myDate}, domNode);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Simplest way to parse a Date in Javascript
I understand how do get the data and break it down into it's segments, i.e.
alert( ( new Date ).getDate() );
and
alert( ( new Date ).getFullYear() );
alert( ( new Date ).getFullMonth() );
etc etc.
But how do I do the same but use a date from a html textbox? instead of reading new Date?
The date in the HTML box would be formated as follows
31/10/2012
You could try:
var datearray = input.value.split("/");
var date = new Date(datearray[2],datearray[1] - 1,datearray[0])
If your textbox has proper string format for a date object you can use:
var aDate = new Date($("textbox").val());
However, if you dont write it in the text box exactly as you would in a string passing to the object, you'll get null for your variable.
FYI, I made a plugin that "extends" the Date object pretty nicely and has preformatted date/times that include things like a basic SQL datetime format.
Just go to this jsFiddle, Copy the code between Begin Plugin and End Plugin into a js file and link it in your header after your jQuery.
The use is as simple as above example:
var aDate = new DateTime($("textbox").val());
And to get a specific format from that you do:
var sqlDate = aDate.formats.compound.mySQL;