what the proper cross-browser date format is for passing to new Date() - date

i did use
var elems = $("#D li").toArray();
elems.sort(function(a, b) {
var adate = new Date($(a).find('div.dateDiv').text());
var bdate = new Date($(b).find('div.dateDiv').text());
return adate > bdate ? -1 : 1;
});
$("#D").html(elems);
<div id="D">
<li>1<div class="dateDiv">2012-04-15 10:25:45</div><div>df</div></li>
<li>2 <div class="dateDiv">2012-04-10 19:41:08</div><div>df</div></li>
<li> 3 <div class="dateDiv">2012-04-20 07:00:10</div><div>ab</div></li>
<li>4 <div class="dateDiv">2012-04-12 16:45:50</div><div>a</div></li>
<li>1<div class="dateDiv">2012-04-15 10:25:45</div></li>
<li>2 <div class="dateDiv">2012-04-10 19:41:08</div></li>
<li> 3 <div class="dateDiv">2012-04-20 07:00:10</div></li>
<li>4 <div class="dateDiv">2012-04-12 16:45:50</div></li>
<li>1<div class="dateDiv">2012-04-15 10:25:45</div></li>
<li>2 <div class="dateDiv">2012-04-10 19:41:08</div></li>
<li> 3 <div class="dateDiv">2012-04-20 07:00:10</div></li>
<li>4 <div class="dateDiv">2012-04-12 16:45:50</div></li>
<li>1<div class="dateDiv">2012-04-15 10:25:45</div></li>
<li>2 <div class="dateDiv">2012-04-10 19:41:08</div></li>
<li> 3 <div class="dateDiv">2012-04-20 07:00:10</div></li>
<li>4 <div class="dateDiv">2012-04-12 16:45:50</div></li>
</div>​
i try it many times
some problem with Firefox browser or IE or safari
it's work only with opera and chrome ,
what the proper cross-browser date format is for passing to new Date() ?

If you can control the date format in the HTML, then it would probably be best to convert it to a timestamp. Otherwise, you'd need to create a function in javascript to convert it to the proper format, whatever that might be.
Instead of doing that, why not just split it up into it's parts and pass the proper arguments to new Date() -- year, month, day, hours, minutes, seconds.
http://jsfiddle.net/katylava/xpjRa/2/
function parseDate(date) {
var date_time = date.split(' ');
var ymd = date_time[0].split('-');
var his = date_time[1].split(':');
return new Date(ymd[0], ymd[1], ymd[2], his[0], his[1], his[2]);
}
var elems = $("#D li").toArray();
elems.sort(function(a, b) {
var adate = parseDate($(a).find('div.dateDiv').text());
var bdate = parseDate($(b).find('div.dateDiv').text());
return adate > bdate ? -1 : 1;
});

Related

jquery DatePicker on specific date

I need to show a datepicker allowing customer to choose multiple dates based on below criteria and also based on business logic that number of Orders can delivery per day.
Show T + 5 days only where T is current date and customer can choose only 5dates in datepicker for delivery. Other dates will be de activated
No Sundays
There will be threshold limit for order delivery. If for example no of orders on specific date met the threshold limit, then that date should be disabled from choosing and show next date for customer to choose for delivery.
$(document).ready( function() {
var threshold_orderlimit = 100; // limit for orders to accept
var tdays = 5; // show today + 5 days
var noOfOrdersPlaced = 40; // current order count
if(noOfOrdersPlaced >= threshold) {
tdays = tdays +1; // next 5 days
}
$("#date").datepicker( {
minDate: +tdays,
maxDate: '+5D', // show only 5 days
beforeShowDay: function(date) { // No sundays
var day = date.getDay();
return [(day != 0), ''];
}
});
});
Can some one help me to check if it is achievable in Jquery Date Picker
In case of using the Jquery Datepicker, its not possible to select multiple dates. Need to add a plugin jQuery MultiDatePicker.
var date = new Date();
var threshold_reached_dates = [date.setDate(15), date.setDate(29),date.setDate(18)];
var today = new Date();
var maximumdays_limit = 5;
var pickable_range = 6;
$("#datepicker").multiDatesPicker({
minDate:today,
beforeShowDay : function(date){ return [date.getDay()!=0,'']},
maxPicks : maximumdays_limit,
pickableRange : pickable_range,
adjustRangeToDisabled: true,
addDisabledDates : threshold_reached_dates
});
function getSelectedDates()
{
console.log($("#datepicker").multiDatesPicker("getDates"))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.css" rel="stylesheet"/>
<link href="https://code.jquery.com/ui/1.12.1/themes/pepper-grinder/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.js"></script>
<div id="datepicker">
<button onclick="getSelectedDates()">Get Selected Dates</button>
In case of using the Bootstrap Datepicker
var startdate = new Date();
var enddate = new Date();
var threshold_reached_dates = ["2018-07-05","2018-07-25","2018-07-13","2018-07-17"];
var maximumdays_limit = 5;
enddate.setDate(startdate.getDate()+maximumdays_limit);
var l = threshold_reached_dates.filter(function(d){return new Date(d)>=startdate && new Date(d)<=enddate;}).length;
(l && enddate.setDate(enddate.getDate()+l));
$('#date').datepicker({
format: "yy-mm-dd",
startDate : startdate,
endDate : enddate,
daysOfWeekDisabled : '0',
datesDisabled: threshold_reached_dates,
multidate: true,
multidateSeparator: ",",
}).on("changeDate",function(event){
var dates = event.dates, elem=$('#date');
if(dates.length>maximumdays_limit)
{
dates.pop();
$("#date").datepicker("setDates",dates)
}
});
function getDates()
{
console.log($("#date").datepicker("getUTCDates"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" rel="stylesheet"/>
<input type="text" id="date">
<button onclick="getDates()">Get Dates</button>

How do I rename files uploaded to an apps script web app form?

I've made a little web app form by splicing together some code I found. It works nearly perfectly for me, allowing me to upload files to a Google Drive folder, logging the data submitted in the form in a spreadsheet and emailing me when a file is uploaded.
However, what I really want to be able to do is to rename the files that are uploaded according to the form data. For example, if the inputted manufacturer value = "Sony" and the date value = 12-04-2016, then make the filename "Sony_12-04-2016.pdf"
From looking it up as best I can it seems I need to pass the submitted values into the createFile() function but I'm quite new to coding and not really sure what I'm doing here..
Here's what I have so far:
.gs
var TO_ADDRESS = "my email address";
function doGet(e) {
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setTitle('Price List Upload Form')
}
function processForm(theForm) {
var fileBlob = theForm.fileUpload;
Logger.log("fileBlob Name: " + fileBlob.getName())
Logger.log("fileBlob type: " + fileBlob.getContentType())
Logger.log('fileBlob: ' + fileBlob);
var fldrSssn = DriveApp.getFolderById('my Google Drive folder id');
fldrSssn.createFile(fileBlob);
return true;
}
function formatMailBody(obj) {
var result = "";
for (var key in obj) {
result += "<h4 style='text-transform: capitalize; margin-bottom: 0'>" + key + "</h4><div>" + obj[key] + "</div>";
}
return result;
}
function doPost(e) {
try {
Logger.log(e);
record_data(e);
var mailData = e.parameters;
MailApp.sendEmail({
to: TO_ADDRESS,
subject: "New Price List Uploaded",
htmlBody: formatMailBody(mailData)
});
return ContentService
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(e.parameters) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) {
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function record_data(e) {
Logger.log(JSON.stringify(e));
try {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName('responses');
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1;
var row = [ new Date() ];
for (var i = 1; i < headers.length; i++) {
if(headers[i].length > 0) {
row.push(e.parameter[headers[i]]);
}
}
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
}
catch(error) {
Logger.log(e);
}
finally {
return;
}
}
.html
<form id="gform" autocomplete="on" method="POST" class="pure-form pure-form-stacked"
action="script url" onsubmit="picUploadJs(this)">
<fieldset class="pure-group">
<input name="fileUpload" type="file" />
</fieldset>
<fieldset class="pure-group">
<label for="manufacturer">Manufacturer: </label>
<input id="manufacturer" name="manufacturer" type="text" placeholder="Manufacturer Name" required/>
</fieldset>
<fieldset class="pure-group">
<label for="issueDate">Date Issued: </label>
<input id="issueDate" name="issueDate" type="date" required />
</fieldset>
<fieldset class="pure-group">
<label for="info">Additional Info: </label>
<input id="info" name="info" type="text" placeholder="Any Additional Information"/>
</fieldset>
<fieldset class="pure-group">
<input id="email" name="email" type="hidden" value="test#gmail.com"/>
</fieldset>
<button class="button-success pure-button button-xlarge">
Upload</button>
<div style="display:none;" id="thankyou_message">
<div id="status" style="display: none">
<h2>Uploading. Please wait...</h2>
</div>
</div>
function picUploadJs(frmData) {
document.getElementById('status').style.display = 'inline';
google.script.run
.withSuccessHandler(updateOutput)
.processForm(frmData)
};
function updateOutput() {
var outputDiv = document.getElementById('status');
outputDiv.innerHTML = "<h2>File successfully uploaded!</h2><button class=\"pure-button\">Upload another</button>";
}
The original code comes from here
and here
I probably don't have all the lingo correct, but you have to turn the form submission fields into variables to be able to use them in your .gs script. Once you turn them into variables, you can "build" a filename to your liking, and use it when writing the fileBlob to a file. Given your code above, you should be able to just modify the processForm function as follows:
function processForm(theForm) {
var fileBlob = theForm.fileUpload;
var manufacturer = theForm.manufacturer;
var issueDate = theForm.issueDate;
var myNewFilename = manufacturer + '_' + issueDate + '.pdf';
fileBlob.setName(myNewFilename); //set Name of the blob
var fldrSssn = DriveApp.getFolderById('my Google Drive folder id');
fldrSssn.createFile(fileBlob); // create a file with the blob, name of the file will be the same as set by setName method
return true;
}
Let me also note something that may be helpful for future visitors--how to write a timestamp into the filename. Set a new variable using the Utilities.formatDate function, and then you can concatenate this variable into a filename like in the example above. Here's how to set the variable:
var myTS = Utilities.formatDate (new Date(), Session.getScriptTimeZone(), "yyyyMMdd_HHmmss--") ;
Format is completely flexible--just look up the function for details.
You may want to use the rename(newName) method which renames the document.
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.rename("This is the new name");
Also, here's a related threads: https://productforums.google.com/forum/#!topic/docs/AP9zMPOyjfg and Copy, rename and move a document which might help.

How do I properly get the date and time?

I am new to react and trying to get the actual date and time but I can't figure out how to do so :(
Could someone help me please !
I try to get the date in the initial state and actualise it every second. When I run it, I get a white screen.
import React from 'react';
import './Menubar.css';
import Time from 'react-time';
const Menubar = React.createClass({
getInitialState() {
return {
now: new Date().now(),
};
},
getRealTime: function() {
this.setState(
{
now: new Date().now(),
})
},
/**
* Render the Menubar component
* #return {Component} the App Component rendered
*/
render() {
setInterval(this.getRealTime(), 1000);
return (
<div className="Menubar">
<ul className="Menubar-menu">
<div className="">
<li className="Menubar-name">login name</li>
<li className="Menubar-date"><Time value={this.state.now} format="DD/MM/YYYY" /></li>
<li className="Menubar-time"><Time value={this.state.now} format="HH:mm:ss" /></li>
</div>
</ul>
</div>
);
}
});
export default Menubar;
Two things:
new Date().now() is not a function, new Date() returns the current date and time, so no need to add it.
You try to set the state inside the render function (calling getRealTime every single render, which causes a re-render). As I understand, you want to update the time every second. You could set that up in componentDidMount.
Here's your Menubar component with those things fixed. I also clear the interval when the component unmounts:
const Menubar = React.createClass({
getInitialState() {
return {
now: new Date(),
};
this.interval = null;
},
componentDidMount: function() {
const self = this;
self.interval = setInterval(function() {
self.setState({
now: new Date(),
});
}, 1000);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
render() {
return (
<div className="Menubar">
<ul className="Menubar-menu">
<div className="">
<li className="Menubar-name">login name</li>
<li className="Menubar-date"><Time value={this.state.now} format="DD/MM/YYYY" /></li>
<li className="Menubar-time"><Time value={this.state.now} format="HH:mm:ss" /></li>
</div>
</ul>
</div>
);
}
});
To just get the current date you can use
var dateVariable = new Date()
dateVariable.getDate()
OR if you want the current Date & Time in full form then,
var dateVariable = Date().toLocaleString()
You can find a comprehensive list of methods available on:
https://hdtuto.com/article/react-js-get-current-date-and-time-example
The above link saved a lot of my time. Hope it works. Happy hacking!
I just want to add to IronmanX46's answer, but it won't let me comment.
I wanted to point out that you can do the exact same thing as
var dateVariable = new Date()
dateVariable.getDate()
var dateVariable = Date().toLocaleString()
by simply doing
var dateVariable = Date()
As per the documentation:
Date()
When called as a function, returns a string representation of the
current date and time. All arguments are ignored. The result is the
same as executing new Date().toString().
There are lots of good websites out there that will give you examples of how to do things, but I find it saves time to just go read the documentation, which usually includes examples. I'll then go check out other examples if I can't understand the documentation.
Date Documentation Link

Selecting angular-ui date-picker value from the calendar using Protractor

My datepicker structure looks like:
<button type="button" class="date-picker-item">
<span>1</span>
</button>
<button type="button" class="date-picker-item">
<span>2</span>
</button>
etc..
I am trying to use by.cssContainingText from the protractor api.
element.all(by.cssContainingText('.date-picker-item > span', day))
but its not selecting it at the minute. Do I need to target this a different way?
Thanks a lot in advance.
In one of my project i wrote function like this:
elementDate: function(inArray,object){
var day = inArray.day.toString();
var cYear = new Date();
var cYear = cYear.getFullYear();
var year = inArray.year;
var month = inArray.month;
object.click();
element(by.css('.btn.btn-sm.btn-danger.uib-clear.ng-binding')).click().then(function(){
return object.click()
});
element(by.css('button[ng-click="toggleMode()"]')).click();
if(cYear > year){
for(var i = cYear; i > year; i--){
object.element(by.css('.btn.btn-default.btn-sm.pull-left.uib-left')).click();
};
}
else if (cYear < year) {
for(var i = cYear; i < year; i++){
object.element(by.css('.btn.btn-default.btn-sm.pull-right.uib-right')).click();
};
}
else{
}
element(by.cssContainingText('.btn.btn-default', month)).click();
element(by.cssContainingText('.uib-day .btn.btn-default.btn-sm', day)).click();
return this;
},
It takes dataPicker element (for example if you would have 2 data pickers one would be name="DatePick1" second name="DatePick2" as element name) and array of date, i think you should only change by.css elements for your project, i recommend to use fireBug to do so

jsTree "select_node" returns false

I am using jsTree in angularjs and using "select_node" in "ready". This method is returning false. On code debugged, it is observed that tree.instance._model.data doesn't have that node so this.get_node(obj); returns false. (below is code snippet)
select_node : function (obj, supress_event, prevent_open, e) {
var dom, t1, t2, th;
if($.isArray(obj)) {
obj = obj.slice();
for(t1 = 0, t2 = obj.length; t1 < t2; t1++) {
this.select_node(obj[t1], supress_event, prevent_open, e);
}
return true;
}
obj = this.get_node(obj); //here it returns false
if(!obj || obj.id === '#') {
return false;
}
}
I am not sure why tree.instance._model.data doesn't have data at that time because it often works when I refresh the browser.
Any help? Below is my code snippet.
me.onTreeReady = function (eve, tree) {
tree.instance.deselect_all();
tree.instance.refresh(true, true);
var response = tree.instance.select_node(defaultNode);
}
This must be some kind of race condition related to your angular directive provider.
This issue has been resolved. I had added "id" to html, so when multiple instances were created with same id it gives the above error. Issue resolved by removing this id.
Old Code
<div class="row no-margin" cg-busy="ctrl.promise">
<div class="bg-white">
<div **id="treeView"** js-tree="ctrl.treeConfig"
should-apply="ctrl.applyModelChanges()"
ng-model="ctrl.treeData"
tree="ctrl.treeInstance"
tree- events="ready:ctrl.onTreeReadyEvent;select_node:ctrl.onNodeSelectEvent;deselect_node:ctrl.onNodeDeselectEvent">
</div>
</div>
</div>
New Code:
<div class="row no-margin" cg-busy="ctrl.promise">
<div class="bg-white">
<div js-tree="ctrl.treeConfig"
should-apply="ctrl.applyModelChanges()"
ng-model="ctrl.treeData"
tree="ctrl.treeInstance"
tree- events="ready:ctrl.onTreeReadyEvent;select_node:ctrl.onNodeSelectEvent;deselect_node:ctrl.onNodeDeselectEvent">
</div>
</div>
</div>