I'm creating an expense tracker application and wanted to get some insight on how to get and save a user's timestamp based on when they click the submit button.
let timestamp = new Date().getTime();
let todate = new Date(timestamp).getDate();
let tomonth = new Date(timestamp).getMonth() + 1;
let toyear = new Date(timestamp).getFullYear();
let original_date = tomonth + "/" + todate + "/" + toyear;
I understand the following code grabs the current date and formats it. If I were to just populate the DOM with original_date based on a click, then it'd work with today's date, but if I check it tomorrow, then it'll grab tomorrow's date. My current problem is, how would I go about saving the date based on a user's submit event without having it update to the current time.
Idea: Would having an event listener for the button be the way to go? Let's say:
function addTransaction(e) {
e.preventDefault();
let saveDate = original_date;
if (text.value.trim() === "" || amount.value.trim() === "") {
alert("Please add a description and amount of the transaction");
} else {
const transaction = {
id: generateID(),
text: text.value,
amount: +amount.value,
date: saveDate
};
transactions.push(transaction);
addTransactionDOM(transaction);
}
}
function addTransactionDOM(transaction) {
const sign = transaction.amount < 0 ? "-" : "+";
//creating new element
const item = document.createElement("li");
//Add class based on value
item.classList.add(transaction.amount < 0 ? "minus" : "plus");
item.innerHTML = `
${transaction.date}
${transaction.text}
${sign}${Math.abs(transaction.amount)}
`;
list.appendChild(item);
}
form.addEventListener("submit", addTransaction);
Would something like this work?
You can save in the browser localStorage the data you need to be retrieved later.
For example:
// Store data
localStorage.setItem('originalDateKey', original_date);
// Get data
var retrievedDate = localStorage.getItem('originalDateKey');
// Remove data
localStorage.removeItem('originalDateKey');
What you need is window.localStorage: localStorage documentation
window.localStorage.setItem(key, value) saves a string value to the user's local storage and can later be accessed with window.localStorage.getItem(key) where key is a unique string identifier.
Here's what I would do to achieve the desired result:
When the page is loaded, check if we have saved a previous date to localStorage
If saved date found, then load it from localStorage into the DOM
Set up a listener for the button which, saves the current date to localStorage (creating a new entry or overwriting the date that was there previously)
Here's some js flavored pseudo code:
// When site fully loaded, check for saved date and load into dom
window.addEventListener("load", function (event) {
const savedTimestamp = window.localStorage.getItem("savedDate");
// If savedTimestamp is null, then we have no previous saved date
if (savedTimestamp !== null) {
// Tip: we can reuse the date object instead of
// creating a new one every time here
const dateObj = new Date(savedTimestamp);
const todate = dateObj.getDate();
const tomonth = dateObj.getMonth() + 1;
const toyear = dateObj.getFullYear();
const savedDate = tomonth + "/" + todate + "/" + toyear;
// Show the saved date, just an example
// Put your code for showing the date here
showSavedDate(savedDate);
}
})
// ... rest of your code
function addTransaction(e) {
// ... omitting for brevity
let saveDate = original_date;
// ...
transactions.push(transaction);
addTransactionDOM(transaction);
// Save the current timestamp to local storage
window.localStorage.setItem("savedDate", saveDate);
}
// ... and so on
Make sure that saveDate is a string when you're saving it to localStorage, otherwise javascript will convert that to a string on its own and possibly screw things up.
Related
When we call 1st time we get the start date of today.Then we wants to set new date and we want to keep the new set date after we call 2nd times.I don't know how to keep history data of date that we set and want to use again.
setCalendar: function() {
var inqYYYY = todate.substring(0, 4);
var inqMM = todate.substring(4, 6);
var inqDD = todate.substring(6, 8);
var inqStrDt = formatter.date(webank.date_minus(todate, 6));
var inqEndDt = inqYYYY + "-" + inqMM + "-" + inqDD;
datePicker.setCalendar("#inq_str_dt");
$("#inq_str_dt").val(inqStrDt);
datePicker.setCalendar("#inq_end_dt");
$("#inq_end_dt").val(inqEndDt);
}
You can set the inqStrDt and inqEndDt into a localStorage ( A persistent storage having lifetime till reset browser storage and history).
You can set the value by
localStorage.setItem('inqStrDt ', inqStrDt);
You can read accoringly as well
let startDate = localStorage.getItem('inqStrDt ');
if(startDate ) {
\\do something
}
Specific situation.. I'm having an array filled with datetimes I pull in via an api.
Users should be able to select a date from a datepicker (only showing dates available in the array) and afterwards see the corresponding time.
So what I've done..
The original array is obtained via php, so before starting to populate the datepicker with possible dates I create an extra array with dates only.
Since I maintain the key's it's possible to put these 2 arrays next to eachother.
Array looks as following:
["8-8-2017,07:00", "26-8-2017,07:00"];
So far so good...
After a user picks a date I trigger this to be able to start digging for the time corresponding that date.
Now it's getting messy...
$('#datepick').datepicker().on("input change", function(e) {
$("#uur").text('');
var selecteddate = e.target.value;
var searchArr = datesArray;
var ind = searchArr.indexOf(selecteddate.toString());
var result = datesArray.filter(function(item) {
return typeof item == 'string' && item.indexOf(selecteddate.toString()) > -1;
});
var afterComma = result.toString().substr(result.toString().indexOf(",") + 1);
var final = afterComma.replace(":", "u");
$("#uur").text("De warming up party gaat van start rond " + final);
});
The result is that this only works on the last element of the array.
Because I'm splitting based on the comma's. Now I know the easiest way to work arround this would be to change the , that's seperating date and time in another symbol but still I'm wondering why this couldn't be easier.
You convert whole array to string every time. You should change following code:
var afterComma = result.toString().substr(result.toString().indexOf(",") + 1);
To this;
var afterComma = item.toString().substr(item.toString().indexOf(",") + 1);
Edit:
I also missed the loop above
//for every item in result, afterComma will refer to related minute string
for (var item in result) {
var afterComma = item.toString().substr(item.toString().indexOf(",") + 1);
// Do rest here
}
Currently, I'm trying to find a way to track the changes of various cell changes with individual time stamps. I want to track changes so that every time one of these rows changes it marks a new time stamp in another column. I need to it to track every time that some make a change with a new time stamp in a new column.
Do you think someone could help me?
This is the function I am using and I was just going to set up a trigger to go off every day. I'm not sure this is the best way to track this type of change either so I am open to other suggestions if anyone has any. The only think is that an onEdit function DOESN'T work when you are using importrange for values. I put an example of the work I'm using here: https://docs.google.com/spreadsheets/d/1PLmkEmJ6sMeu1Y-8mEJ5FaSNIXVnzEuYrilFNA7G0Pk/edit#gid=464181309
.js I was trying to use:
function checkCompleted() {
var s = SpreadsheetApp.getActive().getSheetByName('Sheet1');
s.getRange('G2:H').getValues()
.forEach (function (r, i) {
if(r[0] == 'Completed' && !r[1])
s.getRange(i + 2, 8).setValue(new Date())
})
}
Change tracking Log
The problem with tracking changes by just changing the time stamp is that you only have knowledge of the last change to a given line. So I would suggest just writing a short message into a log entry that you can come back and read anytime. This will include a time stamp, spreadsheet name, sheet name, range changed, oldvalue and new value. You will need to create a file. I use Drive Notepad to create the file and I put all of these sorts of files in one data folder and you'll need the id of the data folder. You'll also need the id of your spreadsheet and the name of the sheet you wish to log the edits of.
You'll need to create an onEdit trigger for the onEditLog function.
The Code:
function onEditLog(e)
{
var ss=e.source.openById('SpreadsheetId');
var docnam=ss.getname();
var shtnam=ss.getActiveSheet().getName();
var range=e.range.getA1Notation();
if(docnam=='Your Document Name' && shtnam=='Sheet1')
{
var msg= 'Spreadsheet: ' + docnam + ' Sheet: ' + shtnam + + 'Range: ' + range + ' has been changed from ' + e.oldvalue + ' to ' + e.value;
logEntry1(msg,'filename');
}
}
function logEntry1(entry,file)//not you cannot run this function like other functions from your script editor. It must be run from an onEdit trigger so that it has access to the event object.
{
var file = (typeof(file) != 'undefined')?file:'eventlog.txt';
var entry = (typeof(entry) != 'undefined')?entry:'No entry string provided.';
if(entry)
{
var ts = Utilities.formatDate(new Date(), "GMT-6", "yyyy-MM-dd' 'hh:mm:ss a");
var s = ts + ' - ' + entry + '\n';
saveFile(s, file, true);
}
}
//this function is taken from myUtility library you'll need to add your own DefaultFileName and DataFolderID.
function saveFile(datstr,filename,append)
{
var append = (typeof(append) !== 'undefined')? append : false;
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;//make change here. It is a string so put quotes around it.
var datstr = (typeof(datstr) !== 'undefined')? datstr : '';
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;//make other change here. Again it is a string
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
if(append)
{
datstr = fi.getBlob().getDataAsString() + datstr;
}
targetFound = true;
fi.setContent(datstr);
}
}
if(!targetFound)
{
var create = fldr.createFile(filename, datstr);
if(create)
{
targetFound = true;
}
}
return targetFound;
}
the Question:
How can I use the API to return a boolean value if the date is a bank holiday?
I have done some research and found a great, and free API which contains bank holidays, however I am having trouble using it: http://holidayapi.com/
if i was to use this code:
var year = 2016;
var month = 3;
var day = 25;
var isAHoliday = false;
$.getJSON(
"http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day, function (data) {
console.log(data); //DOES NOT DISPLAY IN CONSOLE
if (data.holidays.length > 0) {
// BANK HOLIDAY
isAHoliday = true;
}
else {
//IS NOT BANK HOLIDAY
//AND NOTHING NEEDS TO BE DONE
}
});
i want to be able to return a true or false value depending on if this returns any data or not, however im doing something wrong as the getJSON request is not being called, please could someone correct me where i have gone wrong?
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=25 returns {"status":200,"holidays":[{"name":"Good Friday","country":"GB","date":"2016-03-25"}]}
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=26 returns {"status":200,"holidays":[]}
it appears this is causing an issue: "http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day; if i pass one of the 2 URL's in above i get the correct result, I am having a play now with this
https://jsfiddle.net/dcxk6ens/
If you simply want to return a true value if the selected date is a holiday, or false if it is not, you could use a function like this:
(Please note that jsfiddle will not execute any AJAX calls to URLs using the "http://" protocol, since it is not secure.)
function isDateAHoliday(y, m, d) {
var jsonURL = "http://holidayapi.com/v1/holidays?country=GB&year=" + y + "&month=" + m + "&day=" + d;
var isAHoliday = false;
$.getJSON(jsonURL, function (data) {
// If the date is a holiday
if (data.holidays.length > 0) {
// Do some things
isAHoliday = true;
}
// Check values
console.log("JSON DATA: ", data);
console.log("Holiday?: " + isAHoliday);
return isAHoliday;
});
}
isDateAHoliday("2016", "3", "25");
If you wanted to return the name and country of the holiday as well, you could substitute isAHoliday = data.holidays[0]; inside of the if statement.
The holidays object must be called as a child of the returned data object:
Since the holidays object is an array you'll also need to use an index to access an item. Assuming there is at least one item returned, you would get the date like so:
var myDate = data.holidays[0].date;
However you should always check that there's at least one object in the array before getting the first one:
if(data.holidays.length > 0){...}
Incidentally, if all you want to do is check if there's a holiday on any particular day then this if statement is all you'll need, since an array length of more than zero means there's at least one holiday.
Edit
A full answer to your question, you could put this inside the .done() method:
var isAHoliday = false;
if(data.holidays.length > 0){
// There's at least one holiday today!
isAHoliday = true;
}
You don't have to declare a local variable, you'll probably use one that's declared elsewhere but that's up to you.
I have a script for our newspaper that pulls comics from a folder and places them in an InDesign document. Most comics have the full date in the filename, but a few Sunday comics go by the week number for that Sunday. I.E. Blondie sunday filenames are like bln04ts.pdf or bln05ts.pdf. When we run the script we select the day to pull comics for but I'm unsure how to pull these files by week number?
Here is a sample by full date in filename if that helps at all.
` // LUANN
if (pageItem.label == "LUANN")
try{
name = "lu" + myDate.text + ".tif"
var myFile = new File(imagePath+name);
if (myFile.exists)
{
pageItem.place(myFile);
pageItem.fit(FitOptions.CONTENT_TO_FRAME);
}
name = "lu" + myDate.text + "_vacation.tif"
var myFile = new File(imagePath+name);
if (myFile.exists)
{
pageItem.place(File(myFile));
pageItem.fit(FitOptions.CONTENT_TO_FRAME);
}
name = "lu" + myDate.text + "_crx.tif"
var myFile = new File(imagePath+name);
if (myFile.exists)
{
pageItem.place(File(myFile));
pageItem.fit(FitOptions.CONTENT_TO_FRAME);
}
}catch(err){
//alert("caught error")
}`
Any ideas?
Well, if I understand you correctly you would need to add some lines like these to your script:
name = "bln" + myDate.week + "ts.pdf";
var myFile = new File(imagePath+name);
if (myFile.exists)
{
pageItem.place(File(myFile));
pageItem.fit(FitOptions.CONTENT_TO_FRAME);
}
However you'll also need to change the setup of you myDate object to include a week property. I don't know how the myDate object is set up (does it create the date text from the current date? Or from the file name of the document? Or something else?), so you would need to post a snippet of that, if you need further assistance on that step.