I am using jquery easyui edatagrid, where one column is of datebox type editor.
I want to auto select today date so that data entry is faster.
Code :
<th field="date" width="50" editor="{type:'datebox',options:{formatter:myformatter,parser:myparser,required:true}}">Date</th>
function myformatter(date){
var y = date.getFullYear();
var m = date.getMonth()+1;
var d = date.getDate();
return (d<10?('0'+d):d)+'/'+(m<10?('0'+m):m)+'/'+ y;
}
function myparser(s){
if (!s) return new Date();
var ss = (s.split('/'));
var d = parseInt(ss[0],10);
var m = parseInt(ss[1],10);
var y = parseInt(ss[2],10);
if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
return new Date(y,m-1,d);
} else {
return new Date();
}
}
You can set the date as soon as the grid data is loaded. For example, something like
$('.datebox input').each( function(){ $(this).val(formatDate(new Date())) });
It is a matter of getting the input fields. For me the above works, you can adjust it according to your code. Then you need a function that does the date formatting, for example
function formatDate(value) {
return value.getMonth()+1 + "/" + value.getDate() + "/" + value.getYear();
}
Related
Hi I'm using this script to rename every sheet by inserting 'Copy of' in front of the existing sheet name where the text in cell 'B36' = 'SAFETY ANALISIS' and the date from cell 'K3'is older then 30 days. My issue is having to do with the date I can't quite figure how to do it. Cell 'K3' cell are in this format "1-Aug-2021" I think I need to convert the date in 'K3' to a number format.
Any help would be greatly appreciated
function getSheet() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var sum = 0;
for (var i = 0; i < sheets.length ; i++ ) {
var sheet = sheets[i];
var date = new Date();
var ageInDays = 30;
var threshold = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() - ageInDays)
.getTime();
var val = sheet.getRange('K3').getValue();
var val2 = sheet.getRange('B36').getValue();
if (val >= threshold && val2 == 'SAFETY ANALYSIS') {
var sheetName = sheet.getName()
sheet.setName('Copy Of '+sheetName)
}
}
}
You may want to wrap the value you get from cell K3 in a Date() constructor. That should work with spreadsheet dates as well as text strings that look like dates.
I think you have the comparison in val >= threshold the wrong way around. Try something like this:
function renameOldSafetyAnalysisSheets() {
const timeLimit = 30 * 24 * 60 * 60 * 1000; // 30 days
const now = new Date();
const sheets = SpreadsheetApp.getActive().getSheets();
sheets.forEach(sheet => {
if (sheet.getRange('K3').getValue() !== 'SAFETY ANALYSIS') {
return;
}
const date = new Date(sheet.getRange('B36').getValue());
if (!date.getTime()
|| now.getTime() - date.getTime() < timeLimit) {
return;
}
try {
sheet.setName('Copy of ' + sheet.getName());
} catch (error) {
;
}
});
}
function getSheet() {
const shts = SpreadsheetApp.getActive().getSheets();
let d = new Date();
let ageInDays = 30;
let threshold = new Date(d.getFullYear(),d.getMonth(),d.getDate() - ageInDays).valueOf();
shts.forEach(sh => {
let val = new Date(sh.getRange('K3').getValue()).valueOf();
let val2 = sh.getRange('B36').getValue();
if (val <= threshold && val2 == 'SAFETY ANALYSIS') {
sh.setName('Copy Of ' + sh.getName())
}
});
}
When the user select a range of dates on the calendar, a modal opens and the input fields of initial and final dates are auto complete with the dates selected previously. The problem is that they are displaying in this format YYYY-MM-DD and I want it to be DD-MM-YYYY. I have tried everything but nothing seems to work.
Here is where I get the dates and fill the inputs:
select: function (info) {
$('#ModalAdd').modal('show');
$('#ModalAdd').appendTo("body");
$('#activoReservar').val($('#selectActivoReserva option:selected').text());
$('#fechaInicial').val(info.startStr);
var endDate = new Date(info.end);
var beforeDay = new Date(endDate.getFullYear(),endDate.getMonth(),endDate.getDate() - 1).toISOString().slice(0,10);
$('#fechaFinal').val(beforeDay);
},
And here are the things I have tried:
$('#fechaInicial').val(info.startStr.format('ddd, DD-MM-YYYY')); //i tried with dd and a single d too. And without any d
$('#fechaFinal').val(beforeDay.format('ddd, DD-MM-YYYY'));
you may create another function (which you can use anywhere else too),
pass a date to that function and return your desired format.
The sample function might look like as follow:
function dateToDMY(date) {
var d = date.getDate();
var m = date.getMonth() + 1; //Month from 0 to 11
var y = date.getFullYear();
return '' + (d <= 9 ? '0' + d : d) + '-' + (m <= 9 ? '0' + m : m) + '-' + y;
}
And you may call the function from select or any other place as follow:
select: function (selectionInfo) {
var startStr = dateToDMY(selectionInfo.start);
}
Trying to pull a list of ratings from a collection of Reviews and then average them to come up with an aggregated average rating for a Plate. When I look at the data output from the ratings variable I get nothing but "undefined undefined undefined".
averageRating: function() {
var reviews = Reviews.findOne({plateId: this._id});
var ratings = _.pluck(reviews, 'rating');
var sum = ratings.reduce(function(pv, cv){return pv + cv;}, 0);
var avg = sum / ratings.length;
//Testing output
var test = "";
var x;
for (x in reviews) {
text += reviews[x] + ',';
}
return test;
}
Sorry if this is a super newbie question, but I've been at this for hours and cannot figure it out.
I figured out the issue. As listed above var reviews gets set to a cursor which apparently .pluck does not work on. By first converting the cursor to an array of objects I was then able to use .pluck. So updated code looks like this:
averageRating: function() {
var reviewsCursor = Reviews.find({plateId: this._id});
//Converts cursor to an array of objects
var reviews = reviewsCursor.fetch();
var ratings = _.pluck(reviews, 'rating');
var sum = ratings.reduce(function(pv, cv){return pv + cv;}, 0);
var avg = (sum / ratings.length).toPrecision(2);
return avg;
}
I'm trying to get the current date time in Flex/AIR?
To get the current date time, just create a new Date object with no values into the constructor, like this:
var CurrentDateTime:Date = new Date();
Formatting it depends on how you want to format it; here is one option:
private function CurrentDateTimeString():String
{
var CurrentDateTime:Date = new Date();
var CurrentDF:DateFormatter = new DateFormatter();
CurrentDF.formatString = "MM/DD/YY LL:NN:SS A"
var DateTimeString:String = CurrentDF.format(CurrentDateTime);
return DateTimeString;
}
currentTime = new Date();
From : http://livedocs.adobe.com/flex/3/html/help.html?content=08_Dates_and_times_5.html
and
http://docs.huihoo.com/flex/4/Date.html
private function CurrentDateTimeString():String
{
var CurrentDateTime:Date = new Date();
var DateString:String = CurrentDateTime.getMonth().toString()+ "/"+CurrentDateTime.getDate().toString() +"/"+CurrentDateTime.getFullYear().toString();
var TimeString:String = CurrentDateTime.getHours().toString()+ ":"+ doubleDigitFormat(CurrentDateTime.getMinutes());
var DateTimeString:String = DateString + " " + TimeString;
return DateTimeString;
}
function doubleDigitFormat(num:uint):String
{
if(num < 10) {
return ("0" + num);
}
return num.toString();
}
I need to do user validation of a date field, it should be in the format yyyyMMdd and should not be more than one year in the future. How would I go about doing this? Currently I only have a crude regexp which is insufficient.
function VerifyDate(source, args)
{
var regexp = /^([1-2]{1}[0-9]{1})\d{2}([0][1-9]|[1][0-2])([0][1-9]|[1-2][0-9]|[3][0-1])$/
var result = args.Value.match(regexp);
if(result) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
Take the regex to check the format only. You can stay simple:
^(\d{4})(\d{2})(\d{2})$
Then parse the date and check the range:
function VerifyDate(source, args)
{
args.IsValid = false;
var regexp = /^(\d{4})(\d{2})(\d{2})$/;
var daysInMonth = function (y, m) {return 32-new Date(y, m, 32).getDate(); };
var ma = regexp.exec(args.Value);
if (ma && ma.length == 4 && ma[2] < 12 && ma[3] <= daysInMonth(ma[1], ma[2]))
{
var diff = new Date(ma[1], ma[2], ma[3]) - new Date();
args.IsValid = diff < 31536000000; // one year = 1000ms*60*60*24*365
}
}
new Date() don't throw an exception if month or day is out of range. It uses the internal MakeDay to calculate a date (see ECMAScript Language Specification section 15.9.3.1 and 15.9.1.13). To make sure that the date is valid in the function below, the input is converted to integers who is converted to a date, and then the parts of the date are compared to the integers.
Since date uses MakeDay, the calculation of maxDate works even if now is the leep day (xxxx0229 will be yyyy0301 where yyyy=xxxx+1)
function verifyDate(args)
{
var result=false,
match = args.Value.match(/^(\d{4})(\d{2})(\d{2})$/);
if (match && match.length === 4)
{
var year = parseInt(match[1],10),
month =parseInt(match[2],10) -1, // 0 = January
day = parseInt(match[3],10),
testDate= new Date(year,month,day),
now = new Date(),
maxDate = new Date(now.getFullYear() + 1, now.getMonth(), now. getDate()),
minDate = new Date(1800,0,1),
result = (
testDate.getFullYear() === year &&
testDate.getMonth() === month &&
testDate.getDate() === day &&
testDate >= minDate &&
testDate <= maxDate
);
}
args.IsValue = result;
return result;
}
The solution I finally went with is a combination of your answers, I used datejs which seems pretty nice. Here is my final validation function. For some reason the month seems to use a 0 based index so that's why it says -1 in the .set().
function VerifyDate(source, args)
{
args.IsValid = false;
var regexp = /^(\d{4})(\d{2})(\d{2})$/;
var m = regexp.exec(args.Value);
if (m && m.length == 4) {
try {
var result = Date.today().set({ year: Number(m[1]), month: Number(m[2]-1), day: Number(m[3]) });
if (result < Date.today().add({ years: 1 })) {
args.IsValid = true;
}
}
catch (ex) {
}
}
}