Setting value to datetime-local HTML input - javascript

I have an HTML input object of type="datetime-local" to which I would like to set a custom value which is now() + 3 hours everytime its value is changed.
Basing on the fact that alert(object.value) returns a string of type YYYY-MM-DDTHH:MM, I've thought I would need (apart for calculating the date) also to format the string properly. So I have:
Added the onchange attribute to the HTML
<input .... onchange="datesReactions()"/>
Extended the JS Date prototype to add the hours
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Created the datesReactions() function as follows
function datesReaction(){
var adesso = new Date;
document.getElementById('ExecutionDate').value = parseDateToInput(adesso.addHours(3));
}
where the parsing to string is performed by the following simple function:
function parseDateToInput(jsDate){
var jsDay = jsDate.getDate();
if (jsDay < 10){jsDay = '0' + jsDay;}
var jsMonth = jsDate.getMonth();
if (jsMonth < 10){jsMonth = '0' + jsMonth;}
var jsYear = jsDate.getFullYear();
if (jsYear < 10){jsYear = '0' + jsYear;}
var jsHour = jsDate.getHours();
if (jsHour < 10){jsHour = '0' + jsHour;}
var jsMinute = jsDate.getMinutes();
if (jsMinute < 10){jsMinute = '0' + jsMinute;}
return jsYear + '-' + jsMonth + '-' + jsDay + 'T' + jsHour + ':' + jsMinute;
}
However, although the single pieces of code work themselves, the above does nothing when I change the value of my input.
Could anyone please help me understanding what I do wrong? I have prepared the following fiddle in order to help you helping a beginner debugging :) Thanks in advance.

Related

Displaying current & total page number N(N)

I am new to Javascript,so forgive my silly mistakes in advance.
I have a requirement where I have to print current and total page number excluding even pages which are blank.
Example : For 5 page long document,it should display like:
1(3)
2(3)
3(3)
Any sort of info is welcome since I am in dire need of this code to work.
I have tried this but it doesn't work:
var current_page=0 ;
var total_pages=0;
if((current_page<total_pages)||(current_page=total_pages))
{
current_page++;
if(current_page % 2!==0)
{
total_pages++;
}
}
Also, this one too doesn't worked :(
var temp = (this.pageNum) + "(" + (this.numPages) + ")" ;
You have a logical error here:
current_page = total_pages // Note single = symbol between.
You are assigning instead of comparing. Please use == to compare:
current_page == total_pages
Or === for strict comparison as the type of both the variables is same.
Does that help?
function (totalPages, currentPage)
{
if (currentPage%2==1) return "";
var tp = parseInt(totalPages/2+1);
var cp = parseInt(currentPage/2+1);
return "" + cp + "(" + tp + ")";
}

extract and format value in JSON string

I just started working with JSON strings. i have an array of json strings that contains json strings like
{"ID":"3", "LinkFilename":"Test.txt", "Sender":"abc#hotmail.com", "Created":"2014-07-07T20:13:18.000Z"}
what i want to do is to take change the value of "Created" key (which is a date) and omit its time part so it must show only date part. i want to produce something like:
{"ID":"3", "LinkFilename":"Test.txt", "Sender":"abc#hotmail.com", "Created":"2014-07-07"}
The code to produce Json is as follows:
var ItemsEntries = [];
var listItemInfo = '';
var itemsCount = this.collListItem.get_count();
for (i = 0; i < itemsCount; i++) {
var item = this.collListItem.itemAt(i);
var ItemEntry = JSON.stringify(item.get_fieldValues());
ItemsEntries.push(ItemEntry);
listItemInfo += ItemsEntries[i].toString(); + '\n';
}
Please guide me through this.
If you have the Javascript object:
var item = {
"ID":"3",
"LinkFilename":"Test.txt",
"Sender":"abc#hotmail.com",
"Created":"2014-07-07T20:13:18.000Z"
}
and you want to change the Created field in the way you described, you can first create a new Date object out of the Created field value and just extracting the pieces you care about with the functions included in the Date API (http://www.w3schools.com/jsref/jsref_obj_date.asp).
This code should be able to change obj to the format you require:
var formatItem = function(item){
var date = new Date(item["Created"]);
var formattedDate = date.getFullYear()
+ '-'
+ date.getMonth() + 1 // zero-based index...
+ '-'
+ date.getDate();
item["Created"] = formattedDate;
};
One caveat is that the month won't be padded on the left by a 0 if it's a single digit, but that's easy enough to fix on a case-by-case basis.

How to properly sign a GET request to Amazon's ItemLookup using client-side JavaScript only?

Here's what I have so far:
function sha256(stringToSign, secretKey) {
return CryptoJS.HmacSHA256(stringToSign, secretKey);
}
function getAmazonItemInfo(barcode) {
var parameters =
"Service=AWSECommerceService&"
+ "AWSAccessKeyId=" + appSettings.amazon.accessKey + "&"
+ "Operation=ItemLookup&"
+ "ItemId=" + barcode
+ "&Timestamp=" + Date.now().toString();
var stringToSign =
"GET\n"
+ "webservices.amazon.com\n"
+ "/onca/xml\n"
+ parameters;
var signature = "&Signature=" + encodeURIComponent(sha256(stringToSign, appSettings.amazon.secretKey));
var amazonUrl =
"http://webservices.amazon.com/onca/xml?"
+ parameters
+ signature;
// perform a GET request with amazonUrl and do other stuff
}
When executed as an HTTP GET request, the value of amazonUrl in the above code results in the following response from Amazon:
<?xml version="1.0"?>
<ItemLookupErrorResponse xmlns="http://ecs.amazonaws.com/doc/2005-10-05/">
<Error>
<Code>SignatureDoesNotMatch</Code>
<Message>
The request signature we calculated does not match the signature you provided.
Check your AWS Secret Access Key and signing method. Consult the service
documentation for details.
</Message>
</Error>
<RequestId>[REMOVED]</RequestId>
</ItemLookupErrorResponse>
Useful links:
ItemLookup - Product Advertising API Amazon Documentation
Example REST Requests
AWS Authentication Process
CryptoJS
I hacked around with your code and I got it working.
function sha256(stringToSign, secretKey) {
var hex = CryptoJS.HmacSHA256(stringToSign, secretKey);
return hex.toString(CryptoJS.enc.Base64);
}
function timestamp() {
var date = new Date();
var y = date.getUTCFullYear().toString();
var m = (date.getUTCMonth() + 1).toString();
var d = date.getUTCDate().toString();
var h = date.getUTCHours().toString();
var min = date.getUTCMinutes().toString();
var s = date.getUTCSeconds().toString();
if(m.length < 2) { m = "0" + m; }
if(d.length < 2) { d = "0" + d; }
if(h.length < 2) { h = "0" + h; }
if(min.length < 2) { min = "0" + min; }
if(s.length < 2) { s = "0" + s}
var date = y + "-" + m + "-" + d;
var time = h + ":" + min + ":" + s;
return date + "T" + time + "Z";
}
function getAmazonItemInfo(barcode) {
var PrivateKey = "";
var PublicKey = "";
var AssociateTag = "";
var parameters = [];
parameters.push("AWSAccessKeyId=" + PublicKey);
parameters.push("ItemId=" + barcode);
parameters.push("Operation=ItemLookup");
parameters.push("Service=AWSECommerceService");
parameters.push("Timestamp=" + encodeURIComponent(timestamp()));
parameters.push("Version=2011-08-01");
parameters.push("AssociateTag=" + AssociateTag);
parameters.sort();
var paramString = parameters.join('&');
var signingKey = "GET\n" + "webservices.amazon.com\n" + "/onca/xml\n" + paramString
var signature = sha256(signingKey,PrivateKey);
signature = encodeURIComponent(signature);
var amazonUrl = "http://webservices.amazon.com/onca/xml?" + paramString + "&Signature=" + signature;
console.log(amazonUrl);
}
The Header of the Javascript I used for some reference.
<script src="hmac-sha256.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js"></script>
<script src="amazon.js"></script>
You will need to modify parts of it because I changed some parameters around and don't reference your "app" object.
For what I did to fix it (from what I can recall).
The parameters have to be alphabetical. I placed them in an array and then sort them. I follow this up by a join with the ampersand.
I modified the sha256 function to return the base64 of the RAW sha256. Before it was returning the hexbits in lowercase, which isn't correct.
I was going to add a base64 before encoding, but the sha256 now handles all of the signing.
The date format was incorrect. It was returning a epoch timestamp instead of a string timestamp. I hacked together a simple timestamp option.
This code requires you to include the Base64 Library for CryptoJS also.
Use this Node.js library for AWS. It even includes an example specifically for the Product Advertising API.
Building on David's great answer, I made some tweaks. The solution below uses moment.js and crytpo-js, and can be used to search for items by keyword. I used the amazon scratch-pad to help build the target call. A couple of things I noticed:
The scratch-pad needs to use the same location as your associates account, ".com" ".co.uk", etc.
The end point you call to needs to be the same country as your associates account.
The time-stamp you use needs to match the local time in the country your associates account is registered.
const getAmazonItemInfo = (keywords) => {
let date = moment().startOf().add(-9, 'hours').format("YYYY-MM-DDThh:mm:ss.000") + 'Z'
let SecretKey = "GENERATED_IN_AFFILATES_ACCOUNT";
let AccessKey = "GENERATED_IN_AFFILATES_ACCOUNT";
let AssociateTag = "FOUND_IN_AFFILATES_ACCOUNT";
let parameters = [];
let url = 'webservices.amazon.co.uk' // UK account
//let url = 'webservices.amazon.com'// US account
parameters.push("AWSAccessKeyId=" + AccessKey);
parameters.push("Keywords=" + keywords);
parameters.push("Operation=ItemSearch");
parameters.push("SearchIndex=All");
parameters.push("ResponseGroup=" + encodeURIComponent('Images,ItemAttributes,Offers'));
parameters.push("Service=AWSECommerceService");
parameters.push("Timestamp=" + encodeURIComponent(date));
parameters.push("AssociateTag=" + AssociateTag);
parameters.sort();
let paramString = parameters.join('&');
let string_to_sign = "GET\n" + url + "\n" + "/onca/xml\n" + paramString
let signature = CryptoJS.HmacSHA256(string_to_sign, SecretKey);
signature = CryptoJS.enc.Base64.stringify(signature);
let amazonUrl = "http://" + url + "/onca/xml?" + paramString + "&Signature=" + signature;
return amazonUrl;
}
let keywords = 'iphone'
console.log(getAmazonItemInfo(keywords))

Get the next highest date value after excluding values from an array

I have a myDate variable with the value 18-Nov-2013.Each day its value is being changed.Tommorow this myDate variable will have the value 19-Nov-2013.I have a list of values that i have mapped into a single array named exclude which contains some dates that are to be excluded ,now it has values ["20-Nov-2013",21-Nov-2013", "23-Nov-2010"] .How could i filter my value from the list of values from the exclude array.I need the next highest value from the array.So here i need the value 22-Nov-2013 after tommorrows date.Could someone help me with this.
var excluded = ["30-Nov-2013","01-Dec-2013","02-Dec-2013"];
var myDate = "29-Nov-2013";
var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var current = new Date(myDate);
while(true){
current = new Date((current.getDate()+1<10? "0"+(current.getDate()+1):(current.getDate()+1))+ "-" + month[current.getMonth()] + "-" + current.getFullYear());
var checkDate = (current.getDate()<10? "0"+(current.getDate()):(current.getDate()))+ "-" + month[current.getMonth()] + "-" + current.getFullYear();//this is necessary for when the +1 on day of month passes the month barrier
if(-1 == excluded.indexOf(checkDate))
break;
}
alert(checkDate);
I don't know if this is the best approach, or if is the best algorithm, but you may try this:
var myDate = ["17-Nov-2013", "18-Nov-2013"];
var excluded = ["20-Nov-2013", "21-Nov-2013", "23-Nov-2013"];
var months = {"Nov": 10}; // Add others months "Jan": 1, "Fev": 2 etc...
function findExcluded(date)
{
for (var i = 0; i < excluded.length; i++)
{
if (excluded[i] === date)
{
return true;
}
}
return false;
}
function nextDate()
{
var last = myDate[(myDate.length - 1)];
var s = last.split("-");
var d = new Date(s[2], months[s[1]], s[0]);
var next = new Date(d);
var chkDate = "";
do
{
next.setDate(next.getDate() + 1);
chkDate = next.getDate() + "-" + findMonth(next.getMonth()) + "-" + next.getFullYear();
} while(findExcluded(chkDate));
return chkDate;
}
function findMonth(m)
{
var i = 10; // When you fill all months on 'months' array, this variable should start at '0' in order to loop to works.
for (var month in months)
{
if (i == m)
{
return month;
}
i++;
}
}
var nd = nextDate();
alert(nd);
See it woring here.
No code ? Well here will be my method:
1.Get next date for mydate. Say that is var nextDate.
2.Check whether that date exist in the array.
3.If exists add one more day to nextDate. Again check in the array.
4.Do it until you get a date which is not present in your exclude array
For checking whether it exists in the array you can use arrValues.indexOf(nextDateInProperFormat) > -1

javascript function can find another function

I have this below code in a javascript file. When i run it i get error message :
"Can't find variable: addZero".
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate =
new Function("with (this)\n return " +
"getFullYear()+'-'+ addZero(getMonth()+1)+ '-'" +
"+ addZero(getDate()) + 'T' + addZero(getHours())+':' " +
"+ addZero(getMinutes()) +':'+ addZero(getSeconds()) +'.000Z'");
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate = function() {
// do what you want here
// with real code! not strings...
}​
Theres a good function on the Mozilla Javascript reference page for Date that produces ISO Date strings
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z
Looks like your quotes are off. Try
return "with (this)\n return " +
getFullYear() + '-' + addZero(getMonth()+1) + '-' +
addZero(getDate()) + 'T' + addZero(getHours())+':' +
addZero(getMinutes()) +':'+ addZero(getSeconds()) +'.000Z';
Try rewriting your Date extension like this, to keep things clear and to avoid using the with keyword:
Date.prototype.toISODate =
function(){
function padLeft(nr,base,padStr){
base = base || 10;
padStr = padStr || '0';
var len = (String(base).length - String(nr).length)+1;
return len > 0? new Array(len).join(padStr)+nr : nr;
}
return [this.getFullYear(),
'-',
padLeft(this.getMonth()+1),
'-',
padLeft(this.getDate()),
'T',
padLeft(this.getHours()),
':',
padLeft(this.getMinutes()),
':',
padLeft(this.getSeconds()),
'.',
padLeft(this.getMilliseconds(),100),
'Z'].join('');
};
The padLeftZero function now exists within the scope of the Date.toISODate method. The use of an array literal to build the return string is for clarity. It isn't necessary and even can be called bad practice to use new Function ... to assign a function to Date.prototype.toISODate. BTW, milliseconds are added to the result (padded with zero's).

Categories

Resources