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>
Related
Goal
Write a script that does the following:
get data from sheet
modify column to flip names from [Last, First] to [First Last]
modify 2 columns to abbreviate company names & statuses
write resulting data to another spreadsheet without changing the format
add timestamp for when data copied
Problem
I can get the data BUT it writes everything back as plain text. Thus instead of dates writing out as "yyyy-MM-dd", they write out as something like this: Mon Oct 19 2020 01:00:00 GMT-0400 (Eastern Daylight Time)
Expectation:
screenshot of dates as "yyyy-MM-dd"
Result:
screenshot of dates as whatever this garble is
I have googled extensively and can't seem to find a solution. I believe my problem is with using toString() in the Array.map. I'm not sure how to restrict the map method to only the columns that need modifying. Right now it affects the whole array.
(I used the code from Google Apps Script for Multiple Find and Replace in Google Sheets to write this part)
//-----FIND AND REPLACE FOR COMPANY & STATUS ABBREVIATIONS
function replaceInSheet(initArray, to_replace, replace_with){
//Loop over rows in array
for(var row in initArray ){
//Use Array.map to execute a replace call on each of the cells in the row.
var replaced_values = initArray[row].map(function(originalValue){
return originalValue.toString().replace(to_replace,replace_with);
});
//Replace the original row values with the replaced values
initArray[row] = replaced_values;
}
}
Question--> How do I get the output of my script to format dates in two of my columns, correctly?
Attempted Solutions that didn't work
I tried swapping the name flip code to happen after the abbreviation code so I could add a setNumberFormat('yyyy-MM-dd') within the name flip for loop. I couldn't figure out how to apply this to columns within my array. Something like initarray[x][5].setNumberFormat("yyyy-MM-dd") gave me an error saying "TypeError: initArrayx.setNumberFormat is not a function"
I tried adding code before (and then even after) .setValues() at the end to change the format. Some resources I referenced:
setNumberFormat('yyyy-MM-dd') from stackoverflow: Set cell format with google apps script
Utilities.formatDate(new Date(), "CST", "yyyy-MM-dd") from stackoverflow: Get today date in google appScript
website post by BLACKCJ: "Cell Number Formatting with Google Apps Script"
google's developer documentation
and all sorts of other articles, blogs, forums, etc.
I tried writing a completely separate function to change the format after my script runs. Nope. I can't get those 2 columns to format as dates
Code & Sample Spreadsheet
Here's the whole code I'm using, modified to work with a sample google sheet I created just for the purposes of this question.
Sample Google Sheet:
https://docs.google.com/spreadsheets/d/1Ys77hQHHajIo-Xaxyom0SVnyVMZ6bKOT8Smpadd2jv4/edit?usp=sharing
Script:
// ==================================================
// FUNCTION TO RUN
// ==================================================
function syncData(){
//Ger Source Data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("source");
var thisData = thisSheet.getRange("A4:M11");
var initArray = thisData.getValues();
//Get Target Location
var toSheet = ss.getSheetByName("target");
var toRange = toSheet.getRange("A4:M11"); //Range starts at A4
//CHANGE [LAST, FIRST] TO [FIRST LAST]
for (var x = 0; x < initArray.length; x++){
var indexOfFirstComma = initArray[x][0].indexOf(", ");
if(indexOfFirstComma >= 0){
//If comma found, split and update values in the values array
var lastAndFirst = initArray[x][0];
//Update name value in array
initArray[x][0] = lastAndFirst.slice(indexOfFirstComma + 2).trim() + " " + lastAndFirst.slice(0, indexOfFirstComma).trim();
}
}
//ABBREVIATE COMPANY
replaceInSheet(initArray, 'Bluffington School','BLF HS');
replaceInSheet(initArray, 'Honker Burger','HBGR');
replaceInSheet(initArray, 'Funky Town','FT');
//ABBRIVIATE STATUS
replaceInSheet(initArray, 'Regular','Staff');
replaceInSheet(initArray, 'Contractual','Part');
replaceInSheet(initArray, 'Temporary','Temp');
//Clear Target Location
var toClear = toSheet.getRange("A4:M11")
toClear.clearContent();
//Write updated array to target location
toRange.setValues(initArray);
//Write timestamp of when code was last run
setTimeStamp(toSheet);
}
//-----FIND AND REPLACE FOR COMPANY & STATUS ABBREVIATIONS
function replaceInSheet(initArray, to_replace, replace_with){
//Loop over rows in array
for(var row in initArray ){
//Use Array.map to execute a replace call on each of the cells in the row.
var replaced_values = initArray[row].map(function(originalValue){
return originalValue.toString().replace(to_replace,replace_with);
});
//Replace the original row values with the replaced values
initArray[row] = replaced_values;
}
}
//-----ADD TIMESTAMP FOR WHEN THE SCRIPT LAST RAN
function setTimeStamp(toSheet) {
var timestamp = Utilities.formatDate(new Date(), "CST", "yyyy-MM-dd # h:mm a");
toSheet.getRange('F1').setValue(timestamp);
}
setNumberFormat('yyyy-MM-dd') is a good solution but it's a method of a Range of the sheet. Not an array.
To apply the format you need to get a range first. Something like this:
toSheet.getRange('G4:G').setNumberFormat('yyyy-MM-dd');
And there is one more thing ) Try to change this line:
var initArray = thisData.getValues();
to:
var initArray = thisData.getDisplayValues();
I want to add leading Zeros to these single digit days in FullCalendar month view.
What I want is :
Means, 3 as 03, 4 as 04 and so on..
Years later I could not find an option to set the day-number format to one with a leading zero, i did it the same way but without JavaScript in Fullcalendar 5.4.0:
The classname in my case was .fc-daygrid-day-number, I think thats implements the type of the initialized view, whats in my case initialized with: {initialView: 'dayGridMonth'}
Array.prototype.forEach.call(
document.querySelectorAll('.fc-daygrid-day-number'),
function(el) {
if (el.innerText.length === 1) {
el.innerText = '0' + el.innerText;
}
}
)
There doesn't appear to be an option for this in the fullCalendar options curently. Without modifying the fullCalendar source, the best I could come up with is this. If you look at the rendered calendar HTML, you'll see that each day number is wrapped in a <td> with the CSS class fc-day-number. So we can modify the contents of the <td>. Put this code directly after your calendar initialisation code:
$('.fc-day-number').each(function() {
var day = $(this).html(); //get the contents of the td
//for any fields where the content is one character long, add a leading zero
if (day.length == 1)
{
$(this).html("0" + day);
}
});
I had the same problem with React and find this question equivalent. Then I come up with this solution at Fullcalendar 5.6.0:
I used a prop called "dayCellContent" and passed a function to return the formatted string.
<FullCalendar
plugins={[dayGridPlugin]}
initialView="dayGridMonth"
dayCellContent={({ dayNumberText }) => (("00" + dayNumberText).substring(dayNumberText.length))}
/>
Unlike a vanilla date, a moment does not have any required units that must be passed to its constructor. For instance, this is a perfectly valid way to instantiate a moment, with the unpassed units defaulting to current date and 00:00 time:
moment.utc('07:35', 'HH:mm').toISOString();
> "2013-10-24T07:35:00.000Z" //let's just ignore the timezones for now, ok?
So how can partial moments be merged into one? For instance, I could just .set() first moment's hours to values from the second:
var mergee = moment.utc('07:35', 'HH:mm');
moment.utc('2015-01-01').
set('hours', mergee.get('hours')).
set('minutes', mergee.get('minutes')).
toISOString();
> "2015-01-01T07:35:00.000Z" //yay!
But what if I don't know in advance the format of the "mergee", or even what units it has parsed?
While not entirely supported or recommended, something like this will work:
var m1 = moment.utc('07:35', 'HH:mm');
var m2 = moment.utc('2015-01-01');
var merged = moment.utc(m1._i + ' ' + m2._i, m1._f + ' ' + m2._f);
The space separator isn't necessarily required, but it might prevent conflicts with certain formats.
I could see that you might have troubles though if both moments contained the same elements with different data.
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 )
i have been tinkering with the date object.
I want to add a dynamic amount of days to a day and then get the resulting date as a variable and post it to a form.
var startDate = $('#StartDate').datepicker("getDate");
var change = $('#numnights').val();
alert(change);
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + change);
does everything correctly except the last part. it doesnt add the days onto the day
take this scenario:
startdate = 2011-03-01
change = 1
alert change = 1
endDate = 2011-03-11 *it should be 2011-03-02*
thank you to all the quick replies.
converting change variable to an integer did the trick. thank you.
parseInt(change)
just to extend on this: is there a way to assign a variable a type, such as var charge(int)?
You may have fallen victim to string concatenation.
Try changing your last parameter in the Date constructor to: startDate.getDate() + parseInt(change)
See this example for future reference.
convert change to a number before adding it. it looks like you're getting a string concatenation operation rather than the addition you're expectingin your code.
I believe you are concatenating instead of using the mathematical operator. Try this instead,
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + (+change));
It looks like you are not adding the ending day, you are concatinating it so '1' + '1' = '11'
use parseInt() to make sure you are working with integers
example
var change = parseInt($('selector').val());
Also, with this solution, you could easily end up with a day out of range if you are say on a start date of the 29th of the month and get a change of 5