javascript/python time processing fails in chrome - javascript

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.

Related

moment.js not creating right date

I cant seem to figure out what the issue is I have a manual time enter function on my website where a user can enter a time and then I store it in the db..
So my function looks like this..
createTime() {
this.startTime = moment(`${this.hour}:${this.minute} ${this.timeOfDay}`, `HH:mm a`).utc();
}
so I typed in 5:45pm
now when I console.log() the created moment I get this...
so its the right utc time but it says its in AUS TIME
then when I get the time back from the server and then try to convert it back to local time like so..
fixTime(momentObject: moment.Moment) {
return moment(momentObject).local().format('hh:mm A');
}
I get 4:45am
I can not figure out what the issue is.. how can I fix this?
fixTime(momentObject: moment.Moment) {
var testDateUtc = moment.utc(momentObject);
var localDate = moment(testDateUtc).local();
return localDate.format('hh:mm A');
}
you must Create a moment object and set the UTC flag to true on the object and Create a localized moment object converted from the original moment object and finally Return a formatted string from the localized moment
object.
See: http://momentjs.com/docs/#/manipulating/local/

Settnig duration values in jtsage datebox in mode durationflipbox

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 );

Get time using cookies javascript

How to get Time with Cookies javascript When I close the tab or Page?
i'm try use window.onunload but time can not be stored in cookies..
in this code i'm push my cookies to be array
setCookie("time",time,1)
window.onunload =function (){
var set = getCookie('time');
var arr = [];
var push = arr.push(set);
console.log (arr);
return arr;
}
In JavaScript, there is a class called "Date" that let's you get the current time.
var d = new Date(); creates a new Date object and assigns it to the variable d
Now, you have the date and time - you can do whatever you like.
For example: document.getElementById('foo').innerHTML = d.toString() finds the element with the ID of "foo" and sets it's contents to the date and time.
Keep in mind that this date and time display will not constantly update itself. You will have to do that with some timed recursion.
There are many more things you can do with dates. Remember, Google is your friend - look up some things about the Date object.

Moment js split time string

Am using moment JS to get the current time. Based on that time I need execute search operation in my elastic search database.
My database entry is like this way :
"message_date": "2014-03-20T09:17:40.482Z"
Moment code to get current time is like this way :
var m = moment();
var testResult = m.toJSON();
// It outputs : 2014-03-20T09:17:40.482Z
My problem is I don't want to include that seconds filed in my database query. I want to search only up to minute field i.e 2014-03-20T09:17. I can split the moment date to get the expected format. But i know its not the way to do that. Please help me to get the expected time format in moment JS way. Thanks
Try:
var testResult = m.format('YYYY-MM-DD[T]HH:mm');
If you want to get the time in a particular timezone:
var m = moment().zone("+05:30");
var testResult = m.format('YYYY-MM-DD[T]HH:mm');

jQuery Slideshow from XML with date parameters

So I have been tasked with creating a jQuery slideshow from an XML file with a timing mechanism to change the images based on date. I have the slideshow working from the XML, but I am struggling with adding the date feature. I would like to be able to "turn on" and "turn off" images based on the onDate and offDate. I understand Javascript is not the best way to show things based on date, but there are limits within the current site structure that prevent server side timing. So I would like to have the ability to load up say 10 images, and then only show three based on what today's date is, and what the onDate/offDate are.
This is the logic I was thinking.... If today is < onDate .hide or if today is > offDate .hide else .show
Where I am struggling
The correct way to enter the date in the XML file.
Parsing the date from XML into something that Javascript and in turn jQuery can use to compare today's date with the date in XML and show the image accordingly.
Once the date has been established figuring out a way to show or hide the specific image based on date.
Any help would be greatly appreciated.
XML
<eq-banner>
<id>1</id>
<url>linktopage.html</url>
<img>image.jpg</img>
<dept>equipment</dept>
<onDate>12/01/2010</onDate>
<offDate>12/31/2010</offDate>
<copy>FREE Stuff</copy>
</eq-banner>
jQuery
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "rotationData.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(equipment) {
$(equipment).find('eq-banner').each(function() {
var id = $(this).attr('id');
var dept = $(this).find('dept').text();
var url = $(this).find('url').text();
var img = $(this).find('img').text();
$('<div class="'+dept+'"</div>').html('<img src="images/'+img+'" /><br />').appendTo('#apparel')
$("#equipment").cycle({
fx:"fade",
speed:100,
timeout:5000
});;
});
}
</script>
HTML
<div id="equipment">
</div>
If you trust the data quality of the XML source, specifically that the dates are all well-formed as in your sample, it's pretty easy to turn that into a JavaScript "Date" object:
var str = "12/31/2010";
var pieces = str.split('/');
var date = new Date(~~str[2], ~~str[0] - 1, ~~str[1]);
(The ~~ trick converts the strings to numbers; do that however you prefer.) Also months are numbered from zero, and hence the subtraction.
Comparing dates works perfectly well in JavaScript, or you can call the ".getTime()" method on a date to explicitly get a "milliseconds since the epoch" value to compare instead.
As to how you'd show/hide the images, I'd be inclined to conditionally add a class to elements to be hidden (or shown; whichever makes the most sense).
XML doesn't have a "correct" way of handling dates, and JavaScript can parse just about anything. However, the most JS-friendly format would be something like "October 20, 2011" with the time optionally added in "12:34:56" format. A string like that can be fed directly to the new Date() constructor and be parsed correctly regardless of location.
datestr = "October 20, 2011";
date = new Date(datestr);
To compare Date objects, just use < or > -- however, a JS Date object contains a time element which will also be compared. So if you create a new Date object for the present with var now = new Date(); and compare it to var dat = new Date("string with today's date"); you'll find that dat is less than now because dat has time 00:00:00 while now has the present time. If this is a problem, you'll have to explicitly compare Date.getDate(), Date.getMonth() and Date.getFullYear() all at once. ( http://www.w3schools.com/jsref/jsref_obj_date.asp )

Categories