Settnig duration values in jtsage datebox in mode durationflipbox - javascript

I'm having difficulty setting a time (duration) value in a datebox. A simple demonstration of the problem is if I do something like:
function initDuration() {
this.d['header Text'] = "Set";
this.d['headerText'] = "Set Duration";
var element = 'input#'+this.element[0].id;
var currentDt = $(element).datebox('getTheDate');
// ***************
var dt = $(element).datebox('parseDate', '%H:%M', this.element[0].value); // Where this.element[0].value = "01:00:00"
// ***************
$(element).datebox('setTheDate', this.element[0].value);
$(element).trigger('datebox', { 'method': 'doset' });
}
dt just contains the current date/time; i.e. jtsage didn't like it. The element is defined (in jade) as:
input.Duration(type="text" name="duration" form="form#{i}"
id="duration#{i}" value="#{map[i].duration}" data-role="datebox"
data-options=
'{"mode":"durationflipbox", "overrideDurationOrder":["h","i"],'
+' "overrideTimeFormat": "%l:%M", "minuteStep":15, "beforeOpenCallback": "initDuration"}')
Also I'm not sure how to change the flipbox title. The 2nd line in initDuration() sets the text for the button but the title still says 'Set Time'.
Because of the first problem the last 2 lines in initDuration() don't do what I want. i.e. they just use the current time, whatever that happens to be.

My apologies that this is going to be an incomplete answer, but it was going to be too long for a comment.
For the title - give "overrideHeaderText" a shot instead. It is entirely possible that I screwed this up at some point, it's not a feature I use in any of my own projects.
Next...
var dt = $(element).datebox('parseDate', '%H:%M', this.element[0].value); // Where this.element[0].value = "01:00:00"
I think I am reading you correctly that "dt" isn't containing what you are expecting. It's because 01:00:00 != %H:%M - to read this "format", you'd need to either use "%H:%M:%S" or "%H:%M:00" (the later ignoring the seconds field).
That said, I think what you are trying to do is set a duration, which, is a little different. There are a few ways to do it - and I'm noticing that there isn't a lot of support to do it functionally. The simplest method, is the set the value of the input, and let datebox handle the math - just be aware that the format you drop into the input must be exactly the same as the output format - it will read it when the control opens (or is initialized if the control is being shown inline - if you are doing it inline, and set the value "later", you can use the 'refresh' method to update it).
For what it's worth, if you really, really, really want to use the setTheDate method, duration modes work by comparing "theDate" (the publicly available date, i.e. setTheDate, getTheDate) with an internal initDate - which is not exposed to the API, but can be found here:
$(element).data('jtsage-datebox').initDate
So, in pseudo-code, for a duration of an hour
myNewDate = $(element).data( 'jtsage-datebox' ).initDate;
myNewDate.setHour( myNewDate.getHour() + 1 );
$(element).datebox( 'setTheDate', myNewDate );

Related

Avoid choosing previous dates before today, without including today from datapicker on JS and React

I am intending to use a datapicker that does not allow the user to choose previous days before today, but I do want that today itself is available. I did this:
<input
name = "availabilityFrom"
onChange = {(e) => handleDateIn (e.target.value, e.target.name)}
type = "date"
/>
I am working with React so this above is part of a component, that has a state. Then with the value taken, I stored it on a variable to use its valueOf (), and created today´s variable also. Please notice that this.state.filterBy.availabilityFrom holds the value of the target, the selected date on the datapicker.
let today = new Date().valueOf();
let availabilityFromToDate = new Date(this.state.filterBy.availabilityFrom.split("-").join(",")).valueOf();
Then I used a conditional statement to get the desired behavior of the alert:
if (availabilityFromToDate <today && availabilityFromToDate)
{
sweetAlert ("Warning!",
"The entry date must be after the current date";
"warning");
}
It works well, I got so happy when it did. But if I choose today's date, I got the alert message anyway, even if I am not using <= for today.
Maybe I am not understanding the proper use of valueOf (). Been having nightmares about this, haha.
Thanks in advance!: D

javascript function toString'd with dynamic values embedded?

I'm calling toString() on a function so that I can send it across the wire to a system that will apply it against an object. A simplified example is below. Here I am pushing the function as a string to a remote service, which is checking if the remote object this, which has the property timestamp, is older than cutoff which is currently always one house ago...
var functionToSend = function() {
let cutoff = new Date();
cutoff.setHours(autoApproveCutoff.getHours() - 1);
const isMatch = this.timestamp <= cutoff
return isMatch
};
foo.sendFunction(functionToSend.toString())
I'd like to be able to sent the cutoff hour (either at build or runtime), whilst maintaining functionToSend as an actual function so I can unit test and enjoy autocomplete, colourisation etc. Plus, if i end up with 100 checks for 100 different cutoff values I don't want to have to maintain them all separately.
cutoff.setHours(autoApproveCutoff.getHours() - DYNAMIC-VALUE);
Bear in mind that once the function is stringified you can't reference anything external to the function (except thos this which is the remote object).
Might be impossible. Might be more effort than it's worth. But would be interested if anyone has any ideas, short of code-gen.

Set calculated date field to null in podio (and thus with javascript)

Here's the issue with Podio. I have a calculation field that is set to return a date and it does that well if I only enter a reference to a date field from the item. What I want is for the calculation field to return a null date (as part of an IF statement) and thus leave or make the field empty (and therefore not show up in the calendar).
Something like this:
var date = DateFieldFromPodioItem;
if (whatever) {
moment(date).add(2, "weeks").toDate();
}
else {
//RETURN NULL HERE
};
I have tried setting var zero = null and have it return that. Which yields me an Invalid date error.
I also tried using .setFullYear(null,null,null) along with .setHours(null,null,null,null) to set date and return that. I set date to 1 January 0001 12:00:00.000 AM as was suggested somewhere (I forgot where I read that). The first got me a rather unfriendly: Invalid value datetime.datetime(1753, 9, 12, 22, 43, 41, 128000) (datetime): Dates before year 1900 are not supported. The second did too, with slightly different numbers within the ().
I even tried the rather silly idea of entering no code within else, but that also returns Invalid date.
Any ideas?
----EDIT----
Turns out that even while Podio shows the message Invalid date it lets you save the field anyway and when changing field values so if=false it shows no longer a date in the calculation field. Thanks to Rainer Grabowski for pointing that out to me. If someone #Podio reads this, perhaps fix that?
I'll leave this here to perhaps help someone else, as I have found the answer to my questions on here rather often.
Should work, but I didn't test:
var date = DateFieldFromPodioItem;
var returnValue = null;
if (whatever) {
returnValue = moment(date).add(2, "weeks").toDate();
}
returnValue;

JavaScript - Input a date then autopopulate next field with difference

Hi this is making me nuts. I am not a developer. Trying to get this to work.
User puts in a date (hire date) into form using Date object (calendar)
Next field should take that date and subtract todays date to get the length of employment.
But I get undefined in the field AND my original hire date disappears.
Here is what I have, help please, much appreciation!
//grab date of hire
try{document.getElementById("dData_DOH").onchange = custom_calculateDate;}catch(e){}
//not sure if necessary - field that the difference should go to
try{document.getElementById("dData_LengthEmp").onblur = insertDate;}catch(e){}
//Function to grab input hire date
//Create variable for now
//Create variable for difference
function custom_calculateDate(){
var hireDate = document.getElementById("dData_DOH").value = "";
var timeNow= new Date();
var diff = Math.abs(timeNow - hireDate);
document.getElementById("dData_DOH").setAttribute('value', custom_calculateDate());
}
//Function to get the difference into the LengthEmp field
function insertDate() {
document.getElementById("dData_LengthEmp").setAttribute("", custom_calculateDate());
}
I know this is completely wrong, as I said I am not a developer or programmer, I cannot figure out how to get this information into this field and get my original field to still show.
Thank you for reading this!
Use value instead of setAttribute
document.getElementById("dData_DOH").value = custom_calculateDate();
Wow wow wow.
I'll try to rewrite your code by giving you explainations about why:
// Firstly, the onchange event doesn't work on IE for text inputs, prefer onblur
document.getElementById('dData_DOH').onblur = function(e) {
// Now let's get some variables
var hireDate = this.value, // "this" refers to the element that triggered the event
now = new Date(),
// You were on the right track for the difference, almost!
diff = Math.abs(new Date(now.getTime() - hireDate.getTime()))
// Finally, just don't change the original field, but the one you wanted to modify
document.getElementById('dData_LengthEmp').value = diff.toTimeString() // Get the time as a readable format
}
I haven't tested the solution, but it should get you on the track.
Btw, don't use try/catch.

javascript/python time processing fails in chrome

I am writing a timer web app,which records start time and stop time.It uses javascript,jquery1.4.2 for the front end and python for backend code.When a start button is clicked ,start time is saved in a javascript variable.when the button is clicked again, stop time is saved in another variable.These values are passed as hidden parameters to the python code which gets the start,stop values from django's request parameter.
I expect the start/stop parameters values to be in the following format
"07:16:03 PM"
so that it can be parsed using '%I:%M:%S %p'format string.
I am getting this correctly in mozilla firefox.But when I use chrome,I only get
"19:16:03"
This causes value error when I try to parse it with the above format string.
import time
...
def process_input(request,...):
start_time=request.POST[u'timerstarted']
...
fmtstr='%I:%M:%S %p'
start_time_list = list(time.strptime(start_time,fmtstr)[3:6])
I tried putting alert('start time set as'+start_time) in javascript to find what values are set in the page's hiddenfields
With firefox ,I got
start time set as08:03:09 PM
stop time set as08:03:43 PM
but with chrome
start time set as20:04:21
stop time set as20:04:32
My knowledge of javascript,jquery is minimal.Why is the script behaving differently in these two browsers? Below is the javascript snippet
$(document).ready(function(){
var changeBtnStatus=function(){
var timebtnvalue=$('#timebtn').attr("value");
if (timebtnvalue =="start"){
...
var start_date=new Date();
var str_time=start_date.toLocaleTimeString();
var timerstartedfield =$('#timerstarted');
timerstartedfield.attr("value",str_time);
alert('start time set as'+str_time);
}
else if (timebtnvalue=="stop"){
...
var stop_date=new Date();
var stp_time=stop_date.toLocaleTimeString();
var timerstoppedfield =$('#timerstopped');
timerstoppedfield.attr("value",stp_time);
alert('stop time set as'+stp_time);
}
};
var timerBtnClicked=function(){
...
changeBtnStatus();
};
$('#timebtn').click(timerBtnClicked);
...
}
);
You don't want the string of the time in locale, using the toString method you can provide your own format, or use toUTCString().
toLocaleTimeString is especially meant to display the time as the user is used to, you want it in a set format.
So instead of start_date.toLocaleTimeString(), you want to use start_date.toUTCString().
Why format the time in JavaScript and parse in Python, and even submit yourself to the confusion of different locales?
Try using Date.getTime insteam:
start_time = (new Date).getTime();
stop_time = (new Date).getTime();
This gets you the time in milliseconds since the epoch, which should always be stable.

Categories