Is there a way to increment time using javascript? - javascript

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. :)

Related

Difficulties with numeric date offset in luxon

Environment: Win 10 Pro, Chrome 85, luxon 1.25.0
What I am trying to achieve eventually is this: in an ASP.Net/c# application show to the user continuously the amount of time until a session time out will occur. Because server and client may be in different time zones I need the UTC offset of each. The client's offset is easy to get. To find the server's offset (with reference to the code snippet below): the server code puts the page last loaded time into lblLastLoaded. Object dto receives the parsed date parts, including dto.offset which, I gather, is supposed to be expressed in minutes. The subsequent call to luxon.DateTime.fromObject(dto) fails: pst is left undefined. When I do not set dto.offset (by commenting out 4 lines in the code below) pst gets the server time successfully, but without the offset; it appears that luxon uses the offset of my local system which is -7 hours.
<script>
function r4onload() {
// Get server time:
var st = document.getElementById('lblLastLoaded').innerHTML;
// Date Time Offset
// st has form YYYY/MM/dd HH:mm:ss -HH:mm
// 1 2
// 012345678901234567890123456
// For Example 2020/09/29 10:31:56 -07:00
let dto = {};
dto.year = Number(st.substring(0, 4));
dto.month = Number(st.substring(5, 7));
dto.day = Number(st.substring(8, 10));
dto.hour = Number(st.substring(11, 13));
dto.minute = Number(st.substring(14, 16));
var offsetHour = Number(st.substring(20, 23)); // works if these 4 lines are commented out
var offsetMinutes = Number(st.substring(24, 26)); // works if these 4 lines are commented out
dto.offset = offsetHour * 60 + Math.sign(offsetHour) * offsetMinutes; // works if these 4 lines are commented out
// dto.offset is correctly calculated to -420 minutes // works if these 4 lines are commented out
var pst = luxon.DateTime.fromObject(dto);
// pst is undefined at this point -- why??
// If I do not include anything about offset above (comment out the 4 lines
// containing offsetHours, offsetMinutes, and dto.Offset, then pst comes out like this:
// 2020-09-29T10:31:00.00000-07:00
// i.e., luxon used the offset -07:00 of my local system, not the one contained in variable st.
document.getElementById('Parsed').innerHTML = pst;
r4startTime();
}
function r4startTime() {
var dt = luxon.DateTime.local();
var h = dt.hour;
var m = dt.minute;
var s = dt.second;
m = r4checkTime(m);
s = r4checkTime(s);
document.getElementById('CurrTime').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(r4startTime, 2000);
}
function r4checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
A complete Visual Studio 2017 project DemoLuxon with the above code snippet in file Site.Master is here: https://1drv.ms/u/s!AvoFL8QrGVaTsQvbaB8-Zh7GdloV?e=ODjZW5
If the above approach is awkward, I would be grateful for suggestions of more elegant ways of determining the client/server offset difference.
I devised a workaround as follows below, but the original problem has not been answered:
<script>
function r4onload() {
var st = document.getElementById('lblLastLoaded').innerHTML;
// Date Time Offset
// st has form YYYY/MM/dd HH:mm:ss -HH:mm
// 1 2
// 012345678901234567890123456
// For Example 2020/09/29 10:31:56 -07:00
// Transform to ISO format:
st = st.substring(0, 4) + '-' + st.substring(5, 7) + '-' + st.substring(8, 10)
+ 'T' + st.substring(11, 19) + ".000" + st.substring(20);
document.getElementById('Xformed').innerHTML = st;
var pst = luxon.DateTime.fromISO(st, { setZone: true });
document.getElementById('Parsed').innerHTML = pst;
r4startTime();
}
function r4startTime() {
var dt = luxon.DateTime.local();
var h = dt.hour;
var m = dt.minute;
var s = dt.second;
m = r4checkTime(m);
s = r4checkTime(s);
document.getElementById('CurrTime').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(r4startTime, 2000);
}
function r4checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
i.e., put the date-time first into ISO format and then use luxon.DateTime.fromISO. Variable pst gets the correct date-time value including the offset. The problem with luxon.DateTime.fromObject with an offset remains unresolved.

Javascript number like time regex format

I'm receiving from my database time like hh:mm:ss, and in javascript i would like to put the time like hh:mm
this is my code
var time = '10:01:30';
console.log(time);
var res = formatTime(time);
console.log(res);
function formatTime(time) {
var result = false, m;
var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d)\s*$/;
if ((m = time.match(re))) {
result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
console.log(result);
}
}
The function doesn't work well since i receive "false", any help?
Thanks
May be I am missing something in the question, but if you simply want to extract the hh:mm part from hh:mm:ss, then this should work:
// var time = "hh:mm:ss";
var time = "10:01:30";
var splitTime = time.trim().split(":"); // trim to remove any leading and trailing spaces
var formattedTime = splitTime[0] +":"+ splitTime[1];
console.log( formattedTime );
Couldn't you just do the following?:
function formatTime(time) {
var array = time.split(':');
return array[0] + ':' + array[1];
}
The other answer (using split) is undoubtably the easier way to do this.
However, if you're wondering why your regex was not matching, it is because your regular expression was looking for the first (hh) block, and then the second (mm) block, but was then expecting whitespace after that until the end of the line - no allowance for the ss part.
I changed this rather heavy-handedly to allow anything after the mm part until the end of the line. see below.
Also, if you're wondering why your formatTime function returns undefined its because you forgot to return result
var time = '10:01:30';
console.log(time);
var res = formatTime(time);
console.log(res);
function formatTime(time) {
var result = false, m;
var re = /^\s*([01]?\d|2[0-3]):?([0-5]\d).*$/;
if ((m = time.match(re))) {
result = (m[1].length === 2 ? "" : "0") + m[1] + ":" + m[2];
console.log(result);
}
return result;
}
I would consider working with native Date object to do your formatting. This will do a few things for you:
Automatically validate the time value that is being input. No need for regex to do this. Either the input string is valid and the function works, or it is invalid and the function returns NaN.
Give you flexibility in how you work with the value. Need to convert time zones, convert to Unix timestamp, etc.? These are built in methods on Date object.
Gives flexibility on input values. You could potentially you other string input types here if needed as long as they can allow for instantiation of valid Date object. You need to modify regex to allow for multiple input types or anything like that.
Using this approach, example code might look like:
function stripSecondsFromTimeString(time) {
// create data object representing current date
// the date is not really important here other than allowing
// you to format a fully valid Date object with your time fragment
var day = new Date();
var dateInput = day.toDateString() + ' ' + time;
var date = new Date(dateInput);
// validate we were able to get useful Date object
if(isNaN(date.getHours())) {
return NaN;
}
// log out some values so you can see how you might more fully work with Date object
console.log(date.toString());
console.log(date.getDate());
console.log(date.getHours());
console.log(date.getMinutes());
// prepare to return string
var hours = '' + date.getHours();
if(hours.length === 1) {
hours = '0' + hours;
}
var minutes = '' + date.getMinutes();
if(minutes.length === 1) {
minutes = '0' + minutes;
}
return hours + ':' + minutes;
}
// Usage examples
// your input time fragment
var inputTime = '10:01:30';
var formattedTime = stripSecondsFromTimeString(inputTime);
console.log(formattedTime);
// example failure case
var invalidTime = 'foo';
console.log(stripSecondsFromTimeString(invalidTime));

subtract time between two values set in localstorage

I have a quiz program written in vanilla JS. It is supposed to log the time it takes to complete it.
What I would like to achieve is how long it takes for the user to answer the questions by subtraction two variables (strings). If it is even possible.
When the user has stated his name and presses a button "STart Quiz" the currrent time is logged in localstorage like so:
var storeName;
var d = new Date();
var h = getHours();
var m = getMinutes();
var s = getSeconds();
var startTime = h + ":" + m + ":" + s;
var endTime = h + ":" + m + ":" + s;
var result;
var storage = {
storeName: storeName,
startTime: startTime,
endTime: null,
result: result
};
The tricky part is I do not know how to subtract startTime from EndTime to get the time it took to answer the questions. This quiz is over in minutes, so to use the hour is redundant.
When the user has clicked "submit" answer on the last question I want the time logged in LS as endTime.
I hope I have not been unclear and thank you all in advance very much for your time. Thank you.
Instead of storing string as date, directly store the time in milliseconds. Then you can subtract the start time with end time to figure out the time difference.
var startTime = Date.now();
var storage = {
storeName: storeName,
startTime: startTime,
endTime: null,
result: result
};
Later you can calculate the endTime using Date.now() and subtract that from startTime to get the time difference.
storage.endTime = Date.now();
//difference
var diff = storage.endTime - storage.startTime;
You use your new Date() wrong.
Should be this.
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
console.log(h);
As for futher implementation you should save current time then use timer on click/login. After that substract these two values. Example for seconds. You just devide (and/or take a modulo to go to real minutes at current time) by for example 3600 to get seconds instead of an hour. Or you can use all your variable and subtract the time. On the way if you get problems with addition for example you can get 5 + 3 = 53 instead of 8 you use Number(5) + Number(3) to do adition instead of concat. Good luck :P
EDIT: also to get time from your string. With split you get array of value.
var test = h + ":" + m + ":" + s;
console.log(test.split(":"));

JavaScript Time Until

I need to do the simplest thing, take an input date/time and write out the hours:minutes:seconds until that time. I haven't been able to figure it out. I even tried using Datejs which is great, but doesn't seem to have this functionality built in.
The time is going to be somewhere in the range of 0 mins -> 20 minutes
Thanks!
Don't bother with a library for something so simple. You must know the format of the input date string whether you use a library or not, so presuming ISO8601 (like 2013-02-08T08:34:15Z) you can do something like:
// Convert string in ISO8601 format to date object
// e.g. 2013-02-08T02:40:00Z
//
function isoToObj(s) {
var b = s.split(/[-TZ:]/i);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5]));
}
function timeToGo(s) {
// Utility to add leading zero
function z(n) {
return (n < 10? '0' : '') + n;
}
// Convert string to date object
var d = isoToObj(s);
var diff = d - new Date();
// Allow for previous times
var sign = diff < 0? '-' : '';
diff = Math.abs(diff);
// Get time components
var hours = diff/3.6e6 | 0;
var mins = diff%3.6e6 / 6e4 | 0;
var secs = Math.round(diff%6e4 / 1e3);
// Return formatted string
return sign + z(hours) + ':' + z(mins) + ':' + z(secs);
}
You may need to play with the function that converts the string to a date, but not much. You should be providing a UTC timestring anyway, unless you can be certain that the local time of the client is set to the timezone of the supplied datetime value.
Instead of Date.js, try Moment.js.

Is there a reliable way to convert a naive UTC time stamp to local time with javascript?

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.

Categories

Resources