I want to disable the past time from dropdown once user selects date.
Below is the sample code:
function (declare, DateTextBox, locale, dom, lang, registry, ready) {
var pad, update_current_available_times, get_hour_string;
pad = function (n) {
n = n + '';
return n.length >= 2 ? n : new Array(2 - n.length + 1).join('0') + n;
},
get_hour_string = function (t) {
var hour = pad(t.getHours()-1);
var minute = pad(t.getMinutes());
return 'T' + hour + ':' + minute + ':00';
},
For minutes , i changed as below but giving wrong result.But when trying to disable past time from minutes giving unexpected results.
get_hour_string = function (t) {
var hour = pad(t.getHours()-1); //added -1 to disable past time when used dojo1.9
var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 20 );
var minute1 = pad(d2.getMinutes());
alert("d2.getMinutes() : " + d2.getMinutes() );
return 'T' + hour + ':' + minute1 + ':00';
}
Please suggest what are the changes in javascript file need to do to fix disabling past time from minutes dropdown.
Seems to me like you have it almost working..?
If I'm looking at this right, in your hour selector's onChange function, you just need to change:
useMin = 'T02:' + pad(now.getMinutes()) + ':00';
to
useMin = 'T' + pad(v.getHours()) + ':' + pad(now.getMinutes()) + ':00';
Does this work? http://jsfiddle.net/8o23tbLu/27/
Edit: Ah, I see you are using a little trick to only show minutes in the minute dropdown. You could probably just use a dijit/form/Select instead, but it's a nice trick!
Since you have set visibleIncrement and clickableIncrement to 02:05:00 and 02:00:00, what the dropdown is actually showing is:
00:00:00
02:05:00
04:10:00
...
22:55:00
So when setting the minimum constraint on the minute dropdown, you actually have to set the "invisible" hour as well.
As an example, if "now" is 14:34:00, you have to take the 34 minutes, check which 2-hour "group" it belongs to: 34 % 5 = 6ish.
Then get the hour from that: 2 * 6 = 12
.. so the useMin for the minute dropdown in that case would be T12:34:00.
useMin = 'T' +
pad(2 * Math.floor(now.getMinutes() / 5)) + ':' +
pad(now.getMinutes()) + ':00';
At least I think that would do it :) There may be a simpler solution.
Related
I'm trying to create a function that takes a number and returns a timestamp (HH:mm) using date-fns version 1.30.1 or plain JavaScript.
What I'm trying to achieve is to help a user when entering a time. I'm using Vue.js to update the field when a user moves away from the input field. So if a user types 21 then moves away, the field would ideally update to 21:00.
Some examples would be:
21 = 21:00
1 = 01:00
24 = 00:00
2115 = 21:15
Numbers like 815 does not have to return 08:15. Numbers like 7889 should return an error.
I have tried using regex:
time = time
.replace(/^([1-9])$/, '0$1')
.replace(/^([0-9]{2})([0-9]+)$/, '$1:$2')
.replace(/^24/, '00:00')
I have also tried using the parse method in date-fns but can't seem to wrap my head around how to solve this.
Version 1, converting anything less than 100 to hours
const num2time = num => {
if (num < 100) num *=100;
const [_,hh,mm] = num.toString().match(/(\d{1,2})(\d{2})$/)
return `${hh.padStart(2,"0")}:${mm}`
}
console.log(num2time(8));
console.log(num2time(2115));
console.log(num2time(15));
console.log(num2time("8"));
console.log(num2time("2115"));
version 2 can be used if the digits are always representing valid (h)hmm
const num2time = num => num.toString().replace(/(\d{1,2})(\d{2})$/,"$1:$2");
console.log(num2time(815));
console.log(num2time(2115));
console.log(num2time("2115"));
Conversion based on <100 (hours-only) and >=100 (100*hours+minutes), plus some fight with 24 and single-digit numbers (both hours and minutes):
function num2time(num){
var h,m="00";
if(num<100)
h=num;
else {
h=Math.floor(num/100);
m=("0"+(num%100)).slice(-2);
}
h=h%24;
return ("0"+h).slice(-2)+":"+m;
}
console.log(num2time(8));
console.log(num2time(801));
console.log(num2time(24));
console.log(num2time(2401));
console.log(num2time(2115));
console.log(num2time("8"));
console.log(num2time("2115"));
Original answer, kept for the comment only, but would not handle 24 or single-digit minutes correctly:
For example you can do a very mechanical conversion
function num2time(num){
if(num<10)
t="0"+num+":00";
else if(num<100)
t=num+":00";
else {
if(num<1000)
t="0"+Math.floor(num/100);
else if(num<2400)
t=Math.floor(num/100)
else
t="00";
t+=":"+(num%100);
}
return t;
}
console.log(num2time(8));
console.log(num2time(2115));
console.log(num2time("8"));
console.log(num2time("2115"));
Example verification:
function num2time(num){
var h,m="00";
if(num<100)
h=num;
else {
h=Math.floor(num/100);
m=("0"+(num%100)).slice(-2);
}
if(h<0 || h>24) throw "Hour must be between 0 and 24"
if(m<0 || m>59) throw "Minute must be between 0 and 59"
h=h%24;
return ("0"+h).slice(-2)+":"+m;
}
var numstr=prompt("Enter time code");
while(true) {
try {
console.log(num2time(numstr));
break;
} catch(ex) {
numstr=prompt("Enter time code, "+numstr+" is not valid\n"+ex);
}
}
You can use the first char as hour and last char as minute, you've to pad 0 on when there is less than 4 chars.
When there is 1 or 0 char you need to pad both left and right.
When there is 2 or 3 char you only pad right.
time_str = '230'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
time_str = '24'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
time_str = '3'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
time_str = '78'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))
DateFns implementation
IMHO, working on adding and removing minutes and hours is a cleaner way to manage this transform:
function formattedTime(val) {
let helperDate;
if(val.length <= 2) {
if(val > 24)return 'error';
helperDate = dateFns.addHours(new Date(0), val-1);
return dateFns.format(helperDate, 'HH:mm');
}
if(val.length > 2) {
let hhmm = val.match(/.{1,2}/g);
if(hhmm[0] > 24 || hhmm[1] > 60) return 'error';
helperDate = dateFns.addHours(new Date(0), hhmm[0]-1);
helperDate = dateFns.addMinutes(helperDate, hhmm[1]);
return dateFns.format(helperDate, 'HH:mm');
}
}
const myArr = [21, 1, 24, 2115, 815];
myArr.forEach(
val => console.log(formattedTime(val.toString()))
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>
This is an easy thing to do in PHP with code like this;
if (strtotime($given_time) >= time()+300) echo "You are online";
But can't find anything on SO to do exactly this in javascript.
I want to check if the difference between a given time and the current time is less than 45mins
For instance
$scope.given_time = "14:10:00"
$scope.current_time = new Date();
I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.
Then this should be true
How can I achieve this with Javascript:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Javascript uses unix timestamps in milliseconds, so it is similar to the output of strtotime (which uses seconds).
var date = new Date();
Then you'll need to do the calculation from milliseconds. (Minutes * 60 * 1000)
You can also use date.parse() to parse a string to milliseconds, just like strtotime() in PHP does to seconds.
In full:
var date = new Date();
var last = new Date('Previous Date'); // or a previous millisecond timestamp
if ( ( date - last ) > ( 45 * 60 * 1000 ) ) {
// do something
}
You could use a static date to compare just time, this is exactly what strtotime does if you exclude the date:
var last = new Date('1/1/70 14:10:00');
var date = new Date('1/1/70 14:30:00');
However, this approach will fail if you're trying to compare time that cross over day boundaries.
Try this:
function checkTime(time) {
var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
if (minutes > 45 || (minutes < 0 && minutes > -1395)) {
// greater than 45 is todays time is above 45 minutes
// less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
document.write(time + ': true<br />');
} else {
document.write(time + ': false<br />');
}
}
checkTime("14:10:00");
checkTime("16:30:00");
checkTime("17:10:00");
There's a JavaScript method called getMinutes(); you can use to get only the minutes and compare.
Your code should look something like:
var received_time = "14:10:00".split(':');
var minute = '';
if(received_time.length === 3) {
minute = parseInt(received_time[1], 10);
}
$scope.given_time = minute;
var the_time = new Date();
$scope.current_time = the_time.getMinutes();
And you now can do your thing:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Using a library like moment.js you can simply diff the two times.
var $log = $("#log");
/* Difference between just times */
$log.append("Difference between times\n");
var givenTime = moment("14:10:00", "HH:mm:ss");
var minutesPassed = moment("14:30:00", "HH:mm:ss").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
/* Better: Difference between times that have dates attached to them and cross a day boundary. */
$log.append("\n\nDifference between dates with times\n");
givenTime = moment("2015-12-03 23:33:00");
minutesPassed = moment("2015-12-04 00:14:00").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.js"></script>
<p>Results:</p>
<hr>
<pre id="log"></pre>
<hr>
Caveat: If the given time is yesterday such as 11:30pm and the current time is 12:10am then you will get the wrong result. You'd want to use a date with the time if this type of thing is an issue for your use case.
The moment.js documentation
http://momentjs.com/docs/
Angular directive for moment documentation
https://github.com/urish/angular-moment/blob/master/README.md
I am using jqm-calendar for my jquery mobile app. Right now the default time format is 24 hours. I would like to change it to 12 hours.
Thank you.
https://github.com/JWGmeligMeyling/jqm-calendar
In file jw-jqm-cal.js
add this function:
function tConvert (time) {
// Check correct time format and split into components
time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct
time = time.slice (1); // Remove full string match value
time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join (''); // return adjusted time or original string
}
and insert this 2 lines in function plugin.settings.eventHandler.getEventsOnDay(begin, end, function(list_of_events):
beginTime =tConvert(beginTime );
endTime=tConvert(endTime);
EDIT
insert before: timeString = beginTime + "-" + endTime :**
...
beginTime =tConvert(beginTime );
endTime=tConvert(endTime);
timeString = beginTime + "-" + endTime,
...
Determining a user's timezone server side and converting from UTC has proven more trouble than its worth.
Is there a reliable way for javascript/jquery to determine the timezone of the user and apply the offset to a UTC datetime stamp (2012-08-25 10:59:56.511479) and output in my desired format (Aug 25 '12 - 10:59AM)?
What might the jquery code look like to say
// dom ready
$('span.localtime').each(function(e) {
// get stamp and apply conversion
});
.getTimezoneOffset() is available on the date object, and gives you the offset from UTC in minutes.
var offset = (new Date()).getTimezoneOffset();
// convert myUtcDate to a date in local time
myUtcDate.setMinutes(myUtcDate.getMinutes() + (offset*-1));
Thus:
$('.span.localtime').each(function() {
var myUtcDate = new Date($(this).html()); // assuming "2012-08-25 10:59:56.511479"
myUtcDate.setMinutes(myUtcDate.getMinutes() + (myUtcDate.getTimezoneOffset() * -1));
$(this).html(myUtcDate.toString());
});
Note that myUtcDate.toString() could be replaced with any date formatting you want. In your case, it might look like
$(this).html(formatDate(myUtcDate));
function formatDate(d) {
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var y = d.getFullYear().toString().slice(-2); // "12"
var m = months[d.getMonth()]; // "Aug"
var d = d.getDate(); // "25"
var ampm = 'AM';
var h = d.getHours();
if(h>=12) {
h -= 12;
ampm = 'PM';
}
if(h == 0)
h = 12;
var min = ("00" + d.getMinutes()).slice(-2);
return m + " " + d + " '" + y + " - " + h + ":" + min + ampm;
}
You might want to use a date format plugin for formatting dates in a neater more reliable manner.
Also, have a look at https://github.com/GregDThomas/jquery-localtime - it wraps all this up in a simple to use jQuery plugin.
So I am storing times as '01:30:00'. I have a start time and a date time dropdown. I want the dropdown to be set to the start time + 1hr. Is there a way to add the time via javascript or jquery?
Here's my current code:
$(".start_time").change(function(){
$(".end_time").val($(this).val());
});
Try this:
find the selected index of the start time
bump it up by 2 to find your end time index (given that you've got half hour increments)
use the mod operator % to wrap back to index 0 or 1 (for 00:00 and 00:30 respectively)
$(".start_time").change(function(){
var sel =$(this).attr('selectedIndex');
var endIdx = (sel + 2) % 48; // 47 is 23:30, so 48 should go back to index 0
$(".end_time").attr('selectedIndex', endIdx);
});
Try it out on JSBin.
There are two separate problems here: the first is parsing out the time from your .start_time input, and the second is incrementing it to be an hour later.
The first is really a string-manipulation exercise. Once you have parsed out the pieces of the string, e.g. via a regex, you could either turn them into a Date instance and use setHours, or you could just manipulate the components as numbers and them reassemble them into a string in the format you desire.
An example of this might be as follows:
var TIME_PARSING_REGEX = /([0-9]{2}):([0-9]{2}):([0-9]{2})/;
function padToTwoDigits(number) {
return (number < 10 ? "0" : "") + number;
}
$(".start_time").change(function () {
var stringTime = $(this).val();
var regexResults = TIME_PARSING_REGEX.exec(stringTime);
var hours = parseInt(regexResults[1], 10);
var newHours = (hours + 1) % 24;
var newHoursString = padToTwoDigits(newHours);
var minutesString = regexResults[2];
var secondsString = regexResults[3];
var newTimeString = newHoursString + ":" + minutesString + ":" + secondsString;
$(".end_time").val(newTimeString);
});
Basic example...
var date = new Date();
var h = date.getHours() + 1;
var m = date.getMinutes();
var s = date.getSeconds();
alert('One hour from now: ' + h + ':' + m + ':' + s);
Demo: http://jsfiddle.net/fBaDM/2/
After you parse you date/time string, you can use methods such as .setHours in your date object (more info at Mozilla Developer Center).
I highly recommend the DateJS library for working with date and time. I'm sure it'll be very handy for you.
protip: try to avoid replacing JavaScript with "jQuery markup"; it's all JS, after all. :)